欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python自定义线程池控制线程数量的示例

程序员文章站 2022-06-23 20:31:56
1.自定义线程池 import threading import queue import time queue = queue.queue()...

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自定义线程池控制线程数量的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。