脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python自定义线程池控制线程数量的示例

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

2021-06-01 00:06AdgerZhou Python

今天小编就为大家分享一篇python自定义线程池控制线程数量的示例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

1.自定义线程池

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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信号的监控结合

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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自定义线程池控制线程数量的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/qq_18863573/article/details/54090826

延伸 · 阅读

精彩推荐