python线程同步

1 使用Thread对象的Lock和Rlock可以实现简单的线程同步,这两个对象都有acquire方法和release方法,对于那些需要每次只允许一个线程操作的数据,可以将其操作放到acquire和release方法之间。

1.1 对于Lock对象而言,如果一个线程连续两次进行acquire操作,那么第一次acquire之后没有release,第二次acquire将挂起线程。这会导致Lock对象永远不会release,使得死锁

1.2 RLock对象允许一个线程多次进行acquire操作,因为内部通过counter变量维护着线程acquire的次数。而且每一次的acquire操作必须有一个release操作与之对应。在所有release操作完成之后,别的线程才能申请RLock对象。

import threading
mylock = threading.RLock()
num=0
class myThread(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self,name=name)
    def run(self):
        global num
        while True:
            mylock.acquire()
            print '%s locked, Number: %d'%(threading.current_thread().name, num)
            if num>=4:
                mylock.release()
                print '%s released, Number: %d'%(threading.current_thread().name, num)
                break
            num+=1
            print '%s released, Number: %d'%(threading.current_thread().name, num)
            mylock.release()
if __name__== '__main__':
    thread1 = myThread('Thread_1')
    thread2 = myThread('Thread_2')
    thread1.start()
    thread2.start()

C:\Python27\python.exe F:/python_scrapy/python_study/Thread_RLock.py
Thread_1 locked, Number: 0
Thread_1 released, Number: 1
Thread_1 locked, Number: 1
Thread_1 released, Number: 2

Thread_2 locked, Number: 2
Thread_2 released, Number: 3
Thread_1 locked, Number: 3
Thread_1 released, Number: 4
Thread_2 locked, Number: 4
Thread_2 released, Number: 4Thread_1 locked, Number: 4

Thread_1 released, Number: 4

Process finished with exit code 0

全局解释器(GIL)

  • 产生互拆锁限制线程对共享变量的访问,直到次数达到一定时才释放GIL
posted @ 2018-07-31 23:26  大大的大笨熊  阅读(845)  评论(0编辑  收藏  举报