pythonスレッドロック

3090 ワード

スレッド間のランダムスケジューリングのため、あるスレッドはn個のスレッドを実行した後、CPUが他のスレッドを実行する可能性がある.複数のスレッドが1つのメモリ内のリソースを同時に操作するときに混乱しないように、ロックを使用します.
ロック(コマンドロック)は、利用可能な最下位レベルの同期命令である.ロックがロックされている場合、特定のスレッドには所有されません.ロックには、ロックと非ロックの2つの状態と、2つの基本的な方法が含まれています.
ロックにはロックプールがあり,スレッドがロックを要求すると,ロックが得られてからプールを出るまでスレッドをプールに移すと考えられる.プール内のスレッドはステータスマップの同期ブロック状態にあります.
ロックの作成:
lock=threading.Lock()   
cond=threading.Condition(lock=lock)
ロックの方法:
cond.acquire():ロックの取得
cond.wait()通知待ち
cond.notify()通知待機中のロック
cond.notify_all()は、待機中のすべてのロックを通知します.
cond.リリースロック
例:
        ,                ,     。
             ,           ,     ,
    。    ,             。
import threading,time
lista=[]
class huofu(threading.Thread):
    def run(self):
        while True:
            condchi.acquire()    #           
            if len(lista)==0:
                for i in range(1,11):  #    
                    lista.append(i)
                    print("     {}   ".format(i))
                    time.sleep(1)
                condchi.notify_all()      #        ,         
            condchi.release()             #     
class chihuo(threading.Thread):
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.name=name
    def run(self):
        mantou=[]
        while True:
            condchi.acquire()   #             
            if len(lista)>0:
                mantou=lista.pop()  #   
                time.sleep(1)
            else:
                condhuo.acquire()   #      
                condhuo.notify()    #         
                condhuo.release()   #      
                condchi.wait()      #        
            condchi.release()       #      
            if mantou not in lista:
                print("{}   {}   ".format(self.name,mantou))
lock1=threading.Lock()
condhuo=threading.Condition(lock1)
lock2=threading.Lock()
condchi=threading.Condition(lock2)
huofu1=huofu()
chihuo1=chihuo("handao")        #     
chihuo2=chihuo("tanzhenghua")  #     
chihuo3=chihuo("laowang")     #   
huofu1.start()
chihuo1.start()
chihuo2.start()
chihuo3.start()