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实现可设置持续运行时间、线程数及时间间隔的多线程异步post请求功能

Python实现可设置持续运行时间、线程数及时间间隔的多线程异步post请求功能

本文实例讲述了Python实现可设置持续运行时间、线程数及时间间隔的多线程异步post请求功能。分享给大家供大家参考,具体如下: #coding=utf8 ''' random.ra...

python通过微信发送邮件实现电脑关机

Python 通过微信邮件实现电脑关机,供大家参考,具体内容如下 通过手机微信发送QQ邮件给sina邮箱,然后利用python的pop3定时检查sina邮箱的邮件主题以及邮件来源,并在电...

在Python中操作字符串之replace()方法的使用

 replace()方法返回当前old换成new,可选择的替代限制到最大数量的字符串的副本。 语法 以下是replace()方法的语法: str.replace(old,...

PyQt4编程之让状态栏显示信息的方法

赶快记录一下,只是懂皮毛,或许多积累就好了 import sys from PyQt4 import QtGui class MainWindow(QtGui.QMainWindo...

Python遍历pandas数据方法总结

Python遍历pandas数据方法总结

前言 Pandas是python的一个数据分析包,提供了大量的快速便捷处理数据的函数和方法。其中Pandas定义了Series 和 DataFrame两种数据类型,这使数据操作变得更简...