[高分求助]python lock 同步问题

mayer 2016-08-29 11:24:33
请教各位大神,如果两个线程同时去做 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()
...全文
313 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
关山路遥 2016-08-30
  • 打赏
  • 举报
回复
楼主 第六行代码改成self.lock = multiprocessing.Lock()
关山路遥 2016-08-30
  • 打赏
  • 举报
回复
建议楼主看一下python Lock和Semaphore的区别,Lock要求互斥访问,Semaphore用来控制对共享资源的访问数量,不一定互斥,楼主的lock是Semaphore实例化的对象,不能控制不同的线程间的互斥访问

37,718

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧