如何在python中中间的作业中杀死剩余的帖子? 示例代码:
q = Queue.Queue(maxsize=0)
threads = []
max_thread = 10
locker = threading.Semaphore(value=max_thread)
try :
for user in users_list:
t = threading.Thread(target=my_function, args=(user,))
t.setDaemon(True)
threads.append(t)
t.start()
for thread in threads:
q.put(thread)
q.join()
except Exception as errtxt:
print errtxt
该功能例如用于线程池,在此功能中我想收集仅30位用户,支付金额超过5000
def my_function(user):
locker.acquire()
if (user.payment > 5000 ):
collected_users.append(user.id)
if(len(collected_users) >= 30 :
return # <- here i wanna kill other remained threads
q.task_done()
locker.release()
我想我应该在queue /
中设置一个控制器答案 0 :(得分:0)
我试图为我的问题找到解决方案,这是我的代码: 希望有人能做得更好
import Queue , threading
q = Queue.Queue(maxsize=0)
threads = []
max_thread = 10
exitFlag = False
users_id = []
collected_users = []
queueLock = threading.Lock()
for x in range(1,50):
users_id.append(x)
def my_function():
if not q.empty():
ids = q.get()
print (ids)
if (ids < 5000 ):
collected_users.append(ids)
if(len(collected_users) >= 10) :
print ("collected")
exitFlag = True
q.queue.clear()
q.task_done()
else:
q.task_done()
return
try :
for ids in users_id:
q.put(ids)
while not q.empty():
queueLock.acquire()
for workers in range(max_thread):
t = threading.Thread(target=my_function)
t.setDaemon(True)
t.start()
threads.append(t)
for t in threads:
t.join()
queueLock.release()
if (exitFlag == True):
break
print ("All jobs finished")
except Exception as errtxt:
print errtxt