python之多线程简单实例

一、介绍

  Python通过两个标准库thread和threading提供对线程的支持。thread提供了低级别的、原始的线程以及一个简单的锁。
 Thread 是threading模块中最重要的类之一,可以使用它来创建线程。有两种方式来创建线程:一种是通过继承Thread类,重写它的run方法;直接传入要运行的方法。
        Thread模块是比较底层的模块,Threading模块是对Thread做了一些包装的,可以更加方便的被使用。
        另外在工作时,有时需要让多条命令并发的执行, 而不是顺序执行.

二、代码示例

thread模块
# encoding: UTF-8
import thread
import time

# 一个用于在线程中执行的函数
def func():
    for i in range(5):
        print 'func'
        time.sleep(1)

    # 结束当前线程
    # 这个方法与thread.exit_thread()等价
    thread.exit() # 当func返回时,线程同样会结束

# 启动一个线程,线程立即开始运行
# 这个方法与thread.start_new_thread()等价
# 第一个参数是方法,第二个参数是方法的参数
thread.start_new(func, ()) # 方法没有参数时需要传入空tuple

# 创建一个锁(LockType,不能直接实例化)
# 这个方法与thread.allocate_lock()等价
lock = thread.allocate()

# 判断锁是锁定状态还是释放状态
print lock.locked()

# 锁通常用于控制对共享资源的访问
count = 0

# 获得锁,成功获得锁定后返回True
# 可选的timeout参数不填时将一直阻塞直到获得锁定
# 否则超时后将返回False
if lock.acquire():
    count += 1

    # 释放锁
    lock.release()

# thread模块提供的线程都将在主线程结束后同时结束
time.sleep(6)

threading模块
继承Thread类,重写它的run方法,把线程执行的代码放进去就可以
import threading  
import time  
   
class ThreadImpl(threading.Thread):  
    def __init__(self, num):  
        threading.Thread.__init__(self)  
        self._num = num  
   
    def run(self):  
        global total, mutex  
          
        # 打印线程名  
        print(threading.currentThread().getName())  
   
        for x in xrange(0, int(self._num)):  
            # 取得锁  
            mutex.acquire()  
            total = total + 1  
            # 释放锁  
            mutex.release()  
   
if __name__ == '__main__':  
    #定义全局变量  
    global total, mutex  
    total = 0  
    # 创建锁  
    mutex = threading.Lock()  
      
    #定义线程池  
    threads = []  
    # 创建线程对象  
    for x in range(0, 40):  
        threads.append(ThreadImpl(100))  
    # 启动线程  
    for t in threads:  
        t.start()  
    # 等待子线程结束  
    for t in threads:  
        t.join()    
      
    # 打印执行结果  
    print(total)  
直接传入要运行的方法。

# encoding: UTF-8
import threading
import time

def context(tJoin):
    print 'in threadContext.'
    tJoin.start()

    # 将阻塞tContext直到threadJoin终止。
    tJoin.join()

    # tJoin终止后继续执行。
    print 'out threadContext.'

def join():
    print 'in threadJoin.'
    time.sleep(1)
    print 'out threadJoin.'

# tJoin和tContext分别为两个不同的线程
tJoin = threading.Thread(target=join)
tContext = threading.Thread(target=context, args=(tJoin,))

tContext.start()

运行结果:
 in threadContext. 
 in threadJoin. 
 out threadJoin. 
 out threadContext.
如果想具体全面的了解python多线程,推荐一篇博客:
http://blog.csdn.net/luckytanggu/article/details/52183990

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值