【发布时间】:2016-02-09 23:42:17
【问题描述】:
我正在使用Python Thread Pool (Python recipe) 提供的类来模拟线程池。我正在尝试增加函数test 中的值counter。问题是它仍然存在0。我使用了Is this simple python code thread safe 中解释的lock,但仍然无法正常工作。
源代码
#! /usr/bin/python
# -*- coding: utf-8 -*-
from Queue import Queue
from threading import Thread
import threading
lock = threading.Lock()
class Worker(Thread):
"""Thread executing tasks from a given tasks queue"""
def __init__(self, tasks):
Thread.__init__(self)
self.tasks = tasks
self.daemon = True
self.start()
def run(self):
while True:
func, args, kargs = self.tasks.get()
try: func(*args, **kargs)
except Exception, e: print e
self.tasks.task_done()
class ThreadPool:
"""Pool of threads consuming tasks from a queue"""
def __init__(self, num_threads):
self.tasks = Queue(num_threads)
for _ in range(num_threads): Worker(self.tasks)
def add_task(self, func, *args, **kargs):
"""Add a task to the queue"""
self.tasks.put((func, args, kargs))
def wait_completion(self):
"""Wait for completion of all the tasks in the queue"""
self.tasks.join()
def exp1_thread(counter):
with lock:
print counter
counter = counter + 1
def test():
# 1) Init a Thread pool with the desired number of threads
pool = ThreadPool(6)
counter = 0
for i in range(0, 10):
pool.add_task(exp1_thread,counter)
# 3) Wait for completion
pool.wait_completion()
if __name__ == "__main__":
test()
输出
counter 0
counter 0
counter 0
counter 0
counter 0
counter 0
counter 0
counter 0
counter 0
counter 0
【问题讨论】:
-
首先,
counter是test()中的一个局部变量,您需要将它放在脚本的顶部并使其成为全局变量。或者您需要通过调用线程中的函数并获取值来以某种方式更新您的值。 -
哦,好吧,哈哈,但我不知道为什么要把它声明为全局变量?
-
因为如果不将其声明为全局变量,则该变量将不在共享内存空间中,它将在主线程对象中受到“保护”。理论上您可以执行
from threading import enumerate as tenum并访问主线程对象及其变量,然后更新该变量。不建议这样做,但有可能。
标签: python multithreading