AIRobot

AIRobot quick note


  • 首页

  • 关于

  • 标签

  • 分类

  • 归档

  • 搜索

Python控制执行线程数

发表于 2019-07-05 更新于 2019-07-08
本文字数: 607 阅读时长 ≈ 1 分钟

信号量

1
2
3
4
5
6
7
8
9
10
11
12
13
import threading
import time

sem=threading.Semaphore(4)

def gothread():
with sem:
for i in range(8):
print(threading.current_thread().name,i)
time.sleep(1)

for i in range(15):
threading.Thread(target=gothread).start()

使用 with 语句会在它包围的代码块内获取关联的锁。 acquire() 和 release() 方法也能调用关联锁的相关方法。

https://docs.python.org/zh-cn/3.6/library/threading.html
https://docs.python.org/zh-cn/3.6/library/concurrency.html

ThreadPoolExecutor

1
2
3
4
5
6
7
8
9
10
sem=threading.Semaphore(4)

def gothread(s):
time.sleep(s)

pool = ThreadPoolExecutor(max_workers=10)
for i in range(15):
pool.submit(gothread, s)

pool.shutdown(wait=True)
# Python
内存对齐
长耗时任务完成后手机提醒
  • 文章目录
  • 站点概览
AIRobot

AIRobot

AIRobot quick note
130 日志
15 分类
23 标签
GitHub E-Mail
Creative Commons
  1. 1. 信号量
  2. 2. ThreadPoolExecutor
0%
© 2023 AIRobot | 716k | 10:51