圆月山庄资源网 Design By www.vgjia.com

1.自定义线程池

import threading
import Queue
import time
 
queue = Queue.Queue()
 
 
def put_data_in_queue():
  for i in xrange(10):
    queue.put(i)
 
 
class MyThread(threading.Thread):
  def run(self):
    while not queue.empty():
      sleep_times = queue.get()
      time.sleep(sleep_times)
      queue.task_done()
 
 
def main_function():
  threads_num = 6
  while True:
    put_data_in_queue()
    for i in xrange(threads_num):
      myThread = MyThread()
      myThread.setDaemon(True)
      myThread.start()
    queue.join()
    time.sleep(60)

2.多线程与signal信号的监控结合

import threading
import Queue
import time
import signal
 
queue = Queue.Queue()
stop = False
 
 
def receive_signal(signum, stack):
  signal.signal(signal.SIGTERM, original_sigterm)
  global stop
  stop = True
 
 
def put_data_in_queue():
  for i in xrange(10):
    queue.put(i)
 
 
class MyThread(threading.Thread):
  def run(self):
    while not queue.empty():
      sleep_times = queue.get()
      time.sleep(sleep_times)
      queue.task_done()
 
 
def main_function():
  threads_num = 6
  while not stop:
    put_data_in_queue()
    for i in xrange(threads_num):
      myThread = MyThread()
      myThread.setDaemon(True)
      myThread.start()
    queue.join()
    time.sleep(60)
 
 
if __name__ == "__main__":
  original_sigterm = signal.getsignal(signal.SIGTERM)
  signal.signal(signal.SIGTERM, receive_signal)
  main_function()

以上这篇python自定义线程池控制线程数量的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

标签:
python,线程池,线程,数量

圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com