Python多线程

多线程

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
import threading
import time
# 定义最大允许的线程数量
max_threads = 5
# 创建 Semaphore 对象
semaphore = threading.Semaphore(max_threads)
def asyncConcat(startPath, endPath, middlePath, middleAudioPath, outputPath, semaphore):
with semaphore:
thread_id = threading.current_thread().ident
print("Thread ID: ", threading.current_thread().ident)
concat(startPath, endPath, middlePath, middleAudioPath, outputPath)


if __name__ == '__main__':
# 创建线程
threads = []
for file in files:
count = count + 1
basename = os.path.basename(file)
if '.mp4' not in basename:
continue
if '已剪辑' in basename:
continue
if os.path.exists(outputPath + basename.replace('.', '-已剪辑.')):
print('视频已剪辑=', middleDir + basename)
continue
print('待剪辑视频=', middleDir + basename)
fileCount = fileCount + 1
# concat(startPath, endPath, middleDir + basename, middleAudioPath, outputPath)
thread = threading.Thread(target=asyncConcat, args=(
startPath, endPath, middleDir + basename, middleAudioPath, outputPath, semaphore))
threads.append(thread)
thread.start()
# 等待所有线程执行结束
for thread in threads:
thread.join(timeout=1)

获取线程id

1
2
3
import threading
thread_id = threading.current_thread().ident
print("Thread ID: ", thread_id)

设置等待时间

1
2
import threading
thread.join(timeout=1)

线程次 py3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from concurrent.futures import ThreadPoolExecutor
def task(x, y):
time.sleep(1)
return x * y


if __name__ == '__main__':
with ThreadPoolExecutor(max_workers=10) as executor:
future = executor.submit(task, 1, 2)
print(future.result())
future = executor.map(task, [1, 2, 3], [1, 2, 4])
# 等待所有任务完成
executor.shutdown()
for r in future:
print(r)
with ThreadPoolExecutor(max_workers=10) as executor:
futures = [executor.submit(task, i, i) for i in range(5)]
print(all(f.result() for f in futures))
# 等待所有任务完成
executor.shutdown()
print(all(f.result() for f in futures))
for r in futures:
print(r.result())

本文地址: https://github.com/maxzhao-it/blog/post/f4423a86/