我写的一段python线程并发互斥访问的小代码,有点问题看不懂,跪求各位大牛帮忙
时间:2011-06-21
来源:互联网
Python code
上面代码的运行结果是:
the S lock has been locked,wait
。
。
。
。
the S lock has been locked,wait(重复好多遍)
The writer is running
The reader can get the mutex S
The writer is end
这几行应该都没有问题,可见reader和writer是在并发的执行。
但是问题是后面我觉得应该输出一句:The reader is running但这句不输出了,而且程序也就停在这里了不退出,请问是什么原因?是不是我哪里写错了。
#coding=gbk #!/usr/bin/python #Filename:demo2.py import threading import time _DEBUG = True class writer(threading.Thread): '''The class is to simulate the writer thread\ only define the init and run function''' def __init__(self): threading.Thread.__init__(self) def run(self): global mutex,wmutex,S,writecount mutex.acquire() if writecount==0: S.acquire() mutex.release() wmutex.acquire() #perform write operation; print 'The writer is running' wmutex.release() mutex.acquire() writecount = writecount-1 if writecount==0: S.release() mutex.release() print 'The writer is end' class reader(threading.Thread): '''This class is to simulate the reader thread \ only define the init and run function''' def __init__(self): threading.Thread.__init__(self) def run(self): global mutex,S,rmutex,wmutex,readcount while S.locked()==False: print 'the S lock has been locked,wait' print 'The reader can get the mutex S' S.acquire() rmutex.acquire() if readcount==0: wmutex.acquire() readcount=readcount+1 rmutex.release() S.release() #perform read operation; print 'the reader is running' rmutex.acquire() readcount=readcount-1 if readcount==0: wmutex.release() rmutex.release() global mutex,wmutex,rmutex,S,writecount,readcount mutex = threading.Lock() wmutex = threading.Lock() S = threading.Lock() rmutex = threading.Lock() writecount = 0 readcount = 0 threads = [] threads.append(reader()) threads.append(writer()) if _DEBUG==True: print len(threads) for t in threads: t.start()
上面代码的运行结果是:
the S lock has been locked,wait
。
。
。
。
the S lock has been locked,wait(重复好多遍)
The writer is running
The reader can get the mutex S
The writer is end
这几行应该都没有问题,可见reader和writer是在并发的执行。
但是问题是后面我觉得应该输出一句:The reader is running但这句不输出了,而且程序也就停在这里了不退出,请问是什么原因?是不是我哪里写错了。
作者: loveqq1943 发布时间: 2011-06-21
我已经解决了。。。。是因为writer里面漏写了一句writercount = writercount+1。。。管理员大哥,要是看见了就把帖子删除了吧唉。。。
作者: loveqq1943 发布时间: 2011-06-21
自己结贴就完事了。如果你发一个帖子,半个小时之内就发现问题自己解决了,基本说明你在发帖前没有尽全力。在自己努力尝试过解决问题之前尽量不要随意发帖。
作者: iambic 发布时间: 2011-06-21
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28