1

基本上我想在 5 分钟的固定时间内运行 400 个线程。问题是我不知道如何在整个踏板上放置一个计时器(对线程并不熟悉)。到目前为止,我发现的唯一方法是从 JobManager 计时并将停止事件传递给 Job(见下文)。但这会在踏板之间休眠,而不是对整个过程进行计时,然后退出所有线程。

任何想法如何使用 Python 2.7 做到这一点?

import threading, time    

# Job
def Job(i, stop_event):
  print
  print 'Start CountJob nr:', i
  print
  while(not stop_event.is_set()):
    pass
  print 'Job', i, 'exiting'

# run the Jobs
for i in range(0,400):
  p_stop = threading.Event()
  p = threading.Thread(target=Job, args=(i, p_stop))
  p.daemon = True
  p.start()
  time.sleep(10) 
  p_stop.set()
4

1 回答 1

2

You'll need a "super-thread" that you can stop.

import threading, time

# Job
def Job(i, stop_event):
  print
  print 'Start CountJob nr:', i
  print
  while(not stop_event.is_set()):
    pass
  print 'Job', i, 'exiting'


def SuperJob(stop_event):
  for i in range(0,400):
    p = threading.Thread(target=Job, args=(i, stop_event))
    p.daemon = True
    p.start()

    if stop_event.is_set():
      return

# run the Jobs
stop_event = threading.Event()
p = threading.Thread(target=SuperJob, args=(stop_event,))
p.start()
time.sleep(10)
stop_event.set()
于 2013-09-20T14:58:00.177 回答