Multi-thread/process Flashcards

https://qiita.com/eruru/items/b1ac9401755591796f69

1
Q

マルチスレッド

A

結果

https://qiita.com/eruru/items/b1ac9401755591796f69

import concurrent.futures
import time

#1 2 3 4 5を出力する関数
def show_sequence(identifier):
for i in range(1, 6):
print(f”{identifier}: {i}”, flush=True)
time.sleep(0.1)

#6 7 8 9 10を出力する関数
def show_sequence2(identifier):
for i in range(6, 11):
print(f”{identifier}: {i}”, flush=True)
time.sleep(0.2)

#ThreadPoolExecutorを使用してマルチスレッドを実装
with concurrent.futures.ThreadPoolExecutor() as executor:
#スレッドでshow_sequenceを実行
executor.submit(show_sequence, “A”)

#スレッドでshow_sequence2を実行
executor.submit(show_sequence2, "B")

#A: 1
#B: 6
#A: 2
#A: 3
#B: 7
#A: 4
#A: 5
#B: 8
#B: 9
#B: 10

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

マルチプロセス

A

結果

https://qiita.com/eruru/items/b1ac9401755591796f69

import concurrent.futures
import time

# 1 2 3 4 5を出力する関数
def show_sequence(identifier):
for i in range(1, 6):
print(f”{identifier}: {i}”, flush=True)
time.sleep(0.1)

# 6 7 8 9 10を出力する関数
def show_sequence2(identifier):
for i in range(6, 11):
print(f”{identifier}: {i}”, flush=True)
time.sleep(0.2)

# ProcessPoolExecutorを使用してマルチプロセスを実装
with concurrent.futures.ProcessPoolExecutor() as executor:
time.sleep(1)
# プロセスでshow_sequenceを実行
executor.submit(show_sequence, “A”)

# プロセスでshow_sequence2を実行
executor.submit(show_sequence2, "B")

#A: 1
#B: 6
#A: 2
#A: 3
#B: 7
#A: 4
#A: 5
#B: 8
#B: 9
#B: 10

How well did you know this?
1
Not at all
2
3
4
5
Perfectly