python多线程编程的整理perfect

一、比较好的教程:

http://www.ourunix.org/post/199.html


二、示例:

在Python中我们主要是通过thread和threading这两个模块来实现的,其中Python的threading模块是对thread做了一些包装的,可以更加方便的被使用,所以我们使用threading模块实现多线程编程。一般来说,使用线程有两种模式,一种是创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行;另一种是直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的 class里。将函数传递进Thread对象。

数传递进Thread对象
Python代码
'''''
Created on 2012-9-5
@author:  walfred
@module: thread.ThreadTest1
@description:
'''
import threading 
def thread_fun(num): 
for n in range(0, int(num)): 
print " I come from %s, num: %s" %( threading.currentThread().getName(), n) 
def main(thread_num): 
    thread_list = list(); 
# 先创建线程对象
for i in range(0, thread_num): 
        thread_name = "thread_%s" %i 
        thread_list.append(threading.Thread(target = thread_fun, name = thread_name, args = (20,))) 
# 启动所有线程  
for thread in thread_list: 
        thread.start() 
# 主线程中等待所有子线程退出
for thread in thread_list: 
        thread.join() 
if __name__ == "__main__": 
    main(3) 
        程序启动了3个线程,并且打印了每一个线程的线程名字,这个比较简单吧,处理重复任务就派出用场了,下面介绍使用继承threading的方式;
继承自threading.Thread类
Python代码
'''''
Created on 2012-9-6
@author: walfred
@module: thread.ThreadTest2
'''
import threading 
class MyThread(threading.Thread): 
def __init__(self): 
        threading.Thread.__init__(self); 
def run(self): 
print "I am %s" %self.name 
if __name__ == "__main__": 
for thread in range(0, 5): 
        t = MyThread() 
        t.start() 


三、示例:

多线程,海词翻译为multithreading,就是在一个进程中开启多个线程,而后线程之间可以独立运行自己的任务,而不互相干扰。在python中有thread,threading模块可以实现多线程。从官方手册上来看,threading提供了比thread更高级的线程接口,所以建议使用threading模块。

线程开启方法

在threading模块中,开启线程使用如下方法:

1
threading.Thread(group=None, target=None, name=None, args=(), kwargs={})

其中target和args比较常用

  • target 线程执行的方法
  • args 传递给方法的参数,元组对象

简单示例:

#!/usr/bin/env python
#coding=utf8
 
importthreading
 
defloop2():
    fori inrange(10000, 20000):
        printi
 
defloop():
    fori inrange(1, 10000):
        printi
 
#创建两个线程
t =threading.Thread(target=loop)
t2 =threading.Thread(target=loop2)
#线程开始运行
t.start()
t2.start()
#线程挂起,直到线程结束
t.join()
t2.join()

  

运行上面这个程序,可以看到两个线程会交替输出数据,没有什么规则。需要深入使用可以在官网查看详细的资料,使用起来不算很困难,关键还是要用对地方。


用在哪里

多线程其实就是cpu在不同线程之间进行切换执行,因为cpu的计算速度很快,所以看起来好像是同时执行。如果是计算密集型的任务,开启多线程效果反而不好,因为cpu在线程之间的切换也需要消耗。相反,如果是IO密集型的任务,使用多线程效果就很明显了,例如网络数据传输,文件读写等,因为处于IO阻塞时,cpu会等待IO完成,此时基本不消耗cpu资源。


关于python多线程不支持多核的说法

笔者有一次写了一个多线程的程序,发现运行起来,其中一核占用达到100%,其他三核没什么占用,但是会在不同的核心之间切换,一会这个核100%,一会那个核100%。看来网上的说法python线程不支持多核应当是正确的。


四、示例:

Python多线程编程,当程序需要同时并发处理多个任务时,就需要要使用多线程编程。继承线程类threading.thread,再重载成员函数run,程序处理的代码写在函数run中,最后再调用start()方法来运行线程,而join()方法可以用来等待线程结束。

多线程的资源同步,可使用thread.RLock()来创建资源锁,然后使用acquire()来锁住资源,release()来释放资源。等待事件用thread.Event(),用wait()来等待事件,set()来激发事件,clear()用于清除已激发事件。

 例:多线程编程

import time                 # 导入时间模块
import threading as thread  # 导入线程模块

class Thread1(thread.Thread):
    def __init__(self):
        thread.Thread.__init__(self)    # 默认初始化
        self.lock = thread.RLock()      # 创建资源锁
        self.flag = True
        self.count = 0
    def run(self):
        print 'Thread1 run'
        while self.count < 3:
            self.lock.acquire()         # 锁住资源
            self.count += 1
            print self.count            # 输出计数
            self.lock.release()         # 释放资源
            time.sleep(1)               # 线程休眠1秒
        print 'Thread1 end'
        
class Thread2(thread.Thread):
    def __init__(self,event):
        thread.Thread.__init__(self)    # 初始化线程
        self.event = event
    def run(self):
        self.event.wait()               # 线程启动后等待事件
        print 'Thread2 run'
        self.event.clear()              # 清除事件
        print 'Thread2 end'

print 'program start'
event = thread.Event()
t1 = Thread1()
t2 = Thread2(event)
t1.start()              # 线程t1启动
t2.start()              # 线程t2启动
t1.join()               # 等待线程t1结束
event.set()             # 激发事件t2开始运行 
t2.join()               # 等待线程t2结束
print 'program end'     # 结束程序

>> program start		# 输出
>> Thread1 run
>> 1
>> 2
>> 3
>> Thread1 end
>> Thread2 run
>> Thread2 end
>> program end



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值