让我们从一个例子开始:
子类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
语句是获取和释放锁的一种聪明方法,请查看文档。
现在运行代码:
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
通过上面的代码,我们有一个清晰的例子,说明self.count
无论我们做什么都保持不变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()
我希望这可以帮助您澄清一些疑问。