作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
为了避免混淆,我编辑了问题:
一个.py
import threading
count = 5
dev = threading.Thread(name='dev', target=dev,args=(workQueue,count,))
dev.setDaemon(True)
dev.start()
workQueue = Queue.Queue(10)
queueLock.acquire()
workQueue.put(word)
queueLock.release()
count = 3
time.sleep(2)
count = 5
但我在这里的困惑是我能够在线程之间从队列中放入和获取值,但在计数的情况下它不会反射(reflect)出来。
这是为什么?
我实际上在这里缺少什么要点?
class dev ( threading.Thread ):
def test(self):
while 1:
print count
print self.EPP_Obj
queueLock.acquire()
if not self.workQueue.empty():
data = self.workQueue.get()
print data
queueLock.release()
else:
queueLock.release()
def __init__(self, workQueue, EPP_Obj):
threading.Thread.__init__(self)
self.workQueue = workQueue
self.EPP_Obj = EPP_Obj
最佳答案
让我们从一个例子开始:
Thread
子类:
import threading
class Dev(threading.Thread):
def __init__(self, workQueue, queueLock, count):
super(Dev, self).__init__() # super() will call Thread.__init__ for you
self.workQueue = workQueue
self.queueLock= queueLock
self.count = count
def run(self): # put inside run your loop
data = ''
while 1:
with self.queueLock:
if not self.workQueue.empty():
data = self.workQueue.get()
print data
print self.count
if data == 'quit':
break
with
语句是获取和释放锁的一种聪明方法,请查看 doc .
现在运行代码:
import Queue
import time
work_q = Queue.Queue() # first create your "work object"
q_lock = threading.Lock()
count = 1
dev = Dev(work_q, q_lock, count) # after instantiate like this your Thread
dev.setDaemon(True)
dev.start()
time.sleep(1)
with q_lock:
work_q.put('word')
# word
# 1
time.sleep(1)
count = 10
with q_lock:
work_q.put('dog')
# dog
# 1
count = 'foo'
with q_lock:
work_q.put('quit')
# quit
# 1
dev.join() # This will prevent the main to exit
# while the dev thread is still running
通过上面的代码,我们有一个清晰的示例,说明无论我们对 count
做什么,self.count
都是如何保持不变的。
这种行为的原因是调用:
dev = Dev(work_q, q_lock, count)
或
dev = Dev(work_q, q_lock, 1)
是一样的。
Arnold Moon向您展示了一种更改 self.count
的方法。根据我们的示例进行调整:
class Dev(threading.Thread):
def __init__(self, workQueue, queueLock, count):
super(Dev, self).__init__()
self.workQueue = workQueue
self.queueLock= queueLock
self.count = count
def set_count(self, value):
self.count = value
def run(self):
data = ''
while 1:
with self.queueLock:
if not self.workQueue.empty():
data = self.workQueue.get()
print data
print self.count
if data == 'quit':
break
在我们运行的代码中调用set_count
会改变self.count
的值:
time.sleep(1)
with q_lock:
work_q.put('word')
# word
# 1
time.sleep(1)
count = dev.count + 9
dev.set_count(count)
with q_lock:
work_q.put('dog')
# dog
# 10
count = 'foo'
with q_lock:
work_q.put('quit')
# quit
# 10
dev.join()
我希望这能帮助你澄清一些疑问。
关于python - 线程和信息传递——如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9190169/
我是一名优秀的程序员,十分优秀!