我正在尝试学习如何使用Python线程,任何人都可以帮助解决这些令人困惑的部分。
让我们考虑这个例子;假设我们公司有3组工人,工人正在完成任务。我们希望以优化选择的方式影响这些组的任务。
我试图为一组工人构建一个线程对象,所以他们有
class GroupOfWokers:
def __init__(self, n, q,c):
self.name= n
self.q= 0 # number of tasks that we can do // self.q=Queue()
self.capacity= c
def giveTask(self):
#for the second suggestion self.q.put(i)
if self.q<self.capacity:
self.q+=1
return true
else:
return false
def tasks(self):
# how many tasks are you working on
return self.q
在主程序中
g1,g2,g3= GroupOfWokers('G-1',0,9), GroupOfWokers('G-2',0,5), GroupOfWokers('G-3',0,6)
现在,我需要知道如何让它们以并发方式工作。
self.q= 0 # number of tasks that we can do // self.q=Queue()
我应该使用增量变量,还是应该使用queue()。什么是好处? 答案 0 :(得分:0)
混乱可能是由于当前的设计。
您可能想要的是Worker
类,它扩展了threading.Thread
类,并且具有run
方法(使您可以在每个实例上使用Worker.start
来启动它)和它们都消耗的Queue.Queue
实例。
修改 - 这是一个简单的例子:
from threading import Thread
from Queue import Queue
NUMBER_OF_WORKERS = 10
NUMBER_OF_TASKS = 1000
# create tasks
tasks = ['task %d' % i for i in range(NUMBER_OF_TASKS)]
class Worker(Thread):
def __init__(self, name, queue):
super(Worker, self).__init__()
self.task_queue = queue
self.name = name
def run(self):
while True:
task = self.task_queue.get()
if not task == "stop":
print "%s working on %s" % (self.name, task)
else:
print "%s is stopping" % self.name
break
if "__main__" == __name__:
queue = Queue()
workers = [Worker("Worker %d" % i, queue) for i in range(NUMBER_OF_WORKERS)]
for task in tasks:
# put tasks in queue
queue.put(task)
for worker in workers:
# start workers
worker.start()
for worker in workers:
# stop workers
queue.put("stop")
for worker in workers:
# wait for workers
worker.join()