在时间段Y内运行X Python线程

时间:2013-09-20 14:29:06

标签: python multithreading python-multithreading

基本上我想在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()

1 个答案:

答案 0 :(得分:2)

你需要一个可以停止的“超级线程”。

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()
相关问题