我现在用Google搜索了很多内容并没有找到答案 - 这就是我要问的原因。
现在是一天,但是我无法解决一些线程概念,这可能是我的代码混乱的原因。
我正在产生3个线程。精细。
当线程2产生时,线程1"停止"我认为这意味着它会死亡。线程2和3也是一样。
我将这些线程放在活动池中。
我所挣扎的是,让所有3个线程同时运行并等待。我想要一个随机时间间隔为任务分配线程的方法。
从我收集的内容来看,我的线程正在消亡的原因是因为我的工人阶级正在回归。然而,玩过它并把它放在一个循环(1),我仍然无法正常工作。
有什么想法吗?
import logging
import random
import threading
import time
logging.basicConfig(level = logging.DEBUG, format = '(%(threadName)-2s) %(message)s')
class ActivePool(object):
def __init__(self):
super(ActivePool, self).__init__()
self.active = []
self.lock = threading.Lock()
def activate(self, name):
with self.lock:
self.active.append(name)
logging.debug('Running wheel: %s', self.active)
self.move(name)
def move(self, name):
while name.is_alive():
logging.debug('yes')
def inactive(self, name):
with self.lock:
self.active.remove(name)
logging.debug('Running wheel: %s', self.active)
def rtime(self):
self.rt = random.randint(5, 10)
t = threading.Timer(rt, self.revent)
def join(self):
for t in self.active:
t.join()
def check(self):
for t in self.active:
if t.is_alive():
print t
def worker(s, pool):
logging.debug('Wheel inactive')
with s:
#name = threading.currentThread().getName()
thread = threading.currentThread()
logging.debug('ACTIVATING')
pool.activate(thread)
#time.sleep(2)
#pool.inactive(thread)
if __name__ == "__main__":
pool = ActivePool()
s = threading.Semaphore()
for i in range(0, 6):
t = threading.Thread(target = worker, name = str(i + 1), args = (s, pool))
pool.activate(t)
t.start()
logging.debug('here')
答案 0 :(得分:0)
好。我有点重新调整了一些事情。基本上你想要的是这个命令顺序:
您无需加入主题。
如果你确实添加了一个随机任务,你可以将它添加到某个列表中(你必须用你的信号量锁定),工作者函数将从中拉出并执行工作。如果工作人员在列表中看到某些内容,它会将其从列表中删除并执行相关操作。如果无事可做,请让线程休眠。
您可能希望在旋转它们之前将所有线程添加到线程池中(即,在ActivePool中创建一个列表,然后执行pool.activate()并依次激活每个线程)。
import logging
import random
import threading
import time
logger = logging.getLogger("thread_logger")
logger.setLevel(logging.DEBUG)
class ActivePool(object):
def __init__(self):
super(ActivePool, self).__init__()
self.active = []
self.lock = threading.Lock()
def activate(self, name):
with self.lock:
self.active.append(name)
logger.debug('Running wheel: %s', self.active)
t.start()
def inactive(self, name):
with self.lock:
self.active.remove(name)
logger.debug('Running wheel: %s', self.active)
def rtime(self):
self.rt = random.randint(5, 10)
t = threading.Timer(rt, self.revent)
def join(self):
for t in self.active:
t.join()
def check(self):
for t in self.active:
if t.is_alive():
return True
def worker(s, pool):
logger.debug('Worker spinning up')
for x in range(0, 3):
with s:
logger.debug('Thread ID: ' + str(threading.currentThread().ident) + ' DO WORK: ' + str(x))
time.sleep(2)
if __name__ == "__main__":
pool = ActivePool()
s = threading.Semaphore()
for i in range(0, 2):
t = threading.Thread(target = worker, name = str(i + 1), args = (s, pool))
pool.activate(t)
while(pool.check()):
print("Worker thread still workin yo.")
time.sleep(2)
logger.debug('Finito.')