- 論壇徽章:
- 0
|
請(qǐng)教各位大神,如果兩個(gè)線程同時(shí)去做 lock.acquire() ,都可以成功,從而導(dǎo)致同步問(wèn)題。
是我代碼有誤嗎? 還是python線程有Lock的個(gè)數(shù)限制 (實(shí)際代碼中有多個(gè)lock)
示例代碼如下: (估計(jì)要去掉sleep的代碼/加大range范圍才會(huì)跑出來(lái))
- import sys, os, re, time
- import threading
-
- class sockThd(threading.Thread):
- def __init__(self):
- self.lock=threading.Semaphore()
- #self.lock=threading.Lock()
- threading.Thread.__init__(self)
-
- def recv_func(self, id):
- print "before acquire:recv_func(): " + str(id)
- self.lock.acquire()
- print "after acquire:recv_func(): " + str(id)
- time.sleep(1.2)
- print "before release:recv_func(): " + str(id)
- self.lock.release()
-
- def send_func(self, id):
- print "before acquire:send_func(): " + str(id)
- self.lock.acquire()
- print "after acquire:send_func(): " + str(id)
- time.sleep(2)
- print "before release:send_func(): " + str(id)
- self.lock.release()
-
- def run(self):
- for i in range(5):
- self.recv_func(i)
- self.lock.acquire()
- print "after acquire:sock: run(): " + str(i)
- time.sleep(0.7)
- print "before release:sock: run(): " + str(i)
- self.lock.release()
-
- def fileEntry():
- global sth
- for i in range(6):
- print "file: run(0): " + str(i)
- sth.send_func(i)
- print "file: run(1): " + str(i)
- time.sleep(1)
-
- def main():
- global sth
- sth = sockThd()
- fth = threading.Thread(target=fileEntry, args=())
- sth.start()
- fth.start()
- sth.join()
- fth.join()
-
-
- if __name__ == '__main__':
- main()
復(fù)制代碼 |
|