+ -
当前位置:首页 → 问答吧 → 我写的一段python线程并发互斥访问的小代码,有点问题看不懂,跪求各位大牛帮忙

我写的一段python线程并发互斥访问的小代码,有点问题看不懂,跪求各位大牛帮忙

时间:2011-06-21

来源:互联网

Python code

#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