python的多线程实现

在《python核心编程》作者建议尽量少的使用Thread模块用threading替代至于原因我就不多说了:

使用threading的方法就是加载import threading

一,线程相关函数:

1,线程创建:threading.Thread(group=Nonetarget=Nonename=Noneargs=()kwargs={})

其中group设置为nome,target为我们的回调函数,name是为该函数的名称默认为“thread-N”N为数字,args和kwargs为回调函数的参数。

2,python函数需要手动启动使用:start函数

3,join等待线程结束,和linux下的函数一样

4,Thread.is_alive() 判断线程是否激活。(Thread为创建线程时的返回值)

5,threading.active_count() 统计激活线程的个数(threading为加载的库)

个人该觉线程主要相关的比较常用的就这些。

 二,线程的锁:

1,所得创建:lock = threading.Lock(),lock.acquire()获得锁,lock.release()释放锁(对于用法在此我就不做过解释了)

2,条件变量:cond = threading.Condition()

熟悉linux平台的都知道条件变量一般是需要配合一个锁公共使用的,python下也不例外。  cond.acquire(),  cond.release()(同上) cond.wait()等待条件满足(当不满足时释放锁和linux下的条件变量一样)cond.notify()(不是释放锁)通知一个线程,cond.notify_all()(不释放锁)(cond.notifyAll()老版本)通知所有线程。指的注意的是notify这几个函数必须在锁定的情况下使用不然会出错(这个和我们linux下的不一样,我们可以先释放锁再通知)。

notify(n=1)

By default, wake up one thread waiting on this condition, if any. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised.

This method wakes up at most n of the threads waiting for the condition variable; it is a no-op if no threads are waiting.

The current implementation wakes up exactly n threads, if at least n threads are waiting. However, it’s not safe to rely on this behavior. A future, optimized implementation may occasionally wake up more than n threads.

Note: an awakened thread does not actually return from its wait() call until it can reacquire the lock. Since notify() does not release the lock, its caller should.

notify_all()   notifyAll()

Wake up all threads waiting on this condition. This method acts like notify(), but wakes up all waiting threads instead of one. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised.

上面是从官网上摘录的(https://docs.python.org/2/library/threading.html#semaphore-objects

3,条件变量

sem = threading.Semaphore()

sem.acquire()(-1)

sem.release()(+1)

用法就不详述了:

 

#coding:utf-8 
import threading
import time
sem = threading.Semaphore(1)
lock = threading.Lock()  '''全局锁''' 
cond = threading.Condition()  ''' 全局条件变量'''
time1 = 0
count = 0;
def Count1():
    global count
    global cond
    while True:
      # lock.acquire()
        cond.acquire()
        while count == 0:
            cond.wait()
        count = count -1
        print "thread1 have get"
        cond.release()
      
def Count3():
    global count
    global cond
    while True:
        cond.acquire()
        while count==0:
            cond.wait()
        count = count -1
        print "thead3 have get"
        cond.release()
  
def Count2():
    global count;
    global time1
    global cond
    while True:

        cond.acquire()
      
        time.sleep(1)
        if time1 == 10:
            break
        count = count +1;
        time1 = time1 + 1
        cond.notify()
        print "thread2 notyfy"
        print "notify time is****" + str(time1)
        cond.release()
        time.sleep(1)
        
if __name__=="__main__":
    thread1 = threading.Thread(target = Count1)
    thread2 = threading.Thread(target = Count2)
    thread3 = threading.Thread(target = Count3)
    thread1.start()
    thread2.start()
    thread3.start()

    thread2.join()
    
    print "active thread is " + str(threading.active_count())

    print "thread over"
    
    
    


 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值