2013-04-18 50 views
1

我是Python新手。我试图用严格的阅读器优先级来编写读者 - 作者问题,出于某种原因,python不考虑我的全局变量'nor'。线程定义是否存在问题?Python 2.7中的线程

import threading 

readers=threading.BoundedSemaphore(1) 

writers=threading.BoundedSemaphore(1) 

mutex=threading.BoundedSemaphore(1) 

nor=0 
class reader(threading.Thread): 
    def __init__(self): 
     threading.Thread.__init__(self) 
    def run(self): 
     while(1): 
      writers.acquire() 
      mutex.acquire() 
      if(nor==0): 
       readers.acquire() 
      nor=nor+1 
      mutex.release() 

      print "I just read\n" 

      mutex.acquire() 
      if(nor==1): 
       readers.release() 

      nor=nor-1 
      mutex.release() 
      writers.release() 

class writer(threading.Thread): 
    def _init__(self): 
      threading.Thread.__init__(self) 
    def run(self): 
     while(1):   
     writers.acquire() 
     readers.acquire() 

     print "I just wrote\n" 

     writers.release() 
     readers.release() 

r1=reader() 
r2=reader() 
r3=reader() 
w1=writer() 
w2=writer() 

r1.start() 
r2.start() 
r3.start() 
w1.start() 
w2.start() 
+0

Python 17?你的意思是Python 2.7吗? –

+0

是的,错字。坏的一个。 – Shehzaad

回答

2

尝试tiping

global nor 

类里面,也没有调用之前。之后

def run(self): 
+1

说明。赋值适用于本地作用域,除非你向Python提供了你正在搞乱全局的指令。 –

+0

就是这样!感谢您的解释。 –