- 论坛徽章:
- 0
|
请教各位大神,如果两个线程同时去做 lock.acquire() ,都可以成功,从而导致同步问题。
是我代码有误吗? 还是python线程有Lock的个数限制 (实际代码中有多个lock)
示例代码如下: (估计要去掉sleep的代码/加大range范围才会跑出来)
- 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()
复制代码 |
|