当前位置: 动力学知识库 > 问答 > 编程问答 >

multithreading - Run X Python threads for time period Y

问题描述:

Basically I want to run 400 threads for a fixed period of say 5 minutes. Problem is that I don't know how to put a timer on the treads as a whole (not really familiar to threading). The only way to do this that I've found so far is to time from the JobManager and pass a stop event to the Job (see below). But this sleeps between the treads instead of timing the entire process and then exiting all threads.

Any ideas how to do this using 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()

网友答案:

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()
分享给朋友:
您可能感兴趣的文章:
随机阅读: