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

yipeiwu_com5年前Python基础

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设计】。

相关文章

Python数据分析matplotlib设置多个子图的间距方法

注意,要看懂这里,必须具备简单的Python数据分析知识,必须知道matplotlib的简单使用! 例1: plt.subplot(221) # 第一行的左图 plt.subplo...

python类和继承用法实例

本文实例讲述了python类和继承定义与用法。分享给大家供大家参考。具体如下: class Employee: pass lee = Employee() lee.name =...

python实现求特征选择的信息增益

使用python语言,实现求特征选择的信息增益,可以同时满足特征中有连续型和二值离散型属性的情况。 师兄让我做一个特征选择的代码,我在网上找了一下,大部分都是用来求离散型属性的信息益益...

解决tensorflow测试模型时NotFoundError错误的问题

错误代码如下: NotFoundError (see above for traceback): Unsuccessful TensorSliceReader constructor...

Python基于聚类算法实现密度聚类(DBSCAN)计算【测试可用】

Python基于聚类算法实现密度聚类(DBSCAN)计算【测试可用】

本文实例讲述了Python基于聚类算法实现密度聚类(DBSCAN)计算。分享给大家供大家参考,具体如下: 算法思想 基于密度的聚类算法从样本密度的角度考察样本之间的可连接性,并基于可连接...