python - Python 2.7 中的线程

标签 python multithreading global-variables

我是 Python 新手。我尝试用强读者优先级来编写读者-作者问题,由于某种原因,python 不认为我的全局变量“nor”。是不是线程定义有问题?

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()

最佳答案

尝试给小费

global nor

在你的类(class)内,在nor调用之前。之后

def run(self): 

关于python - Python 2.7 中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16086881/

相关文章:

python - 在概率图中设置透明点

python - Matplotlib 是否向我们的命名空间添加变量以及它如何存储数据?

python - 在 pip install MetaTrader5 中找不到“sdkddkver.h”文件

java - 我如何在 Android 的 onResponse 之外使用变量?

python - 跨文件的全局变量和 numpy 行为

python - 将 .py 扩展名转换为可执行文件

java - 多线程socket通信场景

multithreading - NUnit控制台: “WaitAll for multiple handles on a STA thread is not supported” 中的错误

c++ - 插槽在 QT 应用程序中未接收到信号

javascript - 我的脚本中的全局变量和局部变量