Python

Pythonでマルチスレッド

More than 1 year has passed since last update.
from threading import Thread
from threading import Barrier

def function01(barrier, arg1, arg2):
    hoge()
    barrier.wait()
    fuga()

def function02(barrier, argA, argB):
    foo()
    barrier.wait()
    bar()

barrier = Barrier(<threads num>)
threads = []

t = Thread(target=function01, args=(barrier, arg1, arg2))
t.start()
threads.append(t)

t = Thread(target=function02, args=(barrier, argA, argB))
t.start()
threads.append(t)

for t in threads:
   t.join()

Example

from threading import Thread
from threading import Barrier
from time import sleep

def function01(barrier):
    print('START function01 !')
    barrier.wait()
    for i in range(5):
        sleep(0.5)
        print('A')
    print('FINISH function01 !')

def function02(barrier):
    print('START function02 !')
    barrier.wait()
    for i in range(5):
        sleep(0.5)
        print('B')
    print('FINISH function02 !')

def function03(barrier):
    print('START function03 !')
    barrier.wait()
    for i in range(5):
        sleep(0.5)
        print('C')
    print('FINISH function03 !')

barrier = Barrier(3)
threads = []

t = Thread(target=function01, args=(barrier,))
t.start()
threads.append(t)

t = Thread(target=function02, args=(barrier,))
t.start()
threads.append(t)

t = Thread(target=function03, args=(barrier,))
t.start()
threads.append(t)

for t in threads:
   t.join()

# >>> START function01 !
# >>> START function02 !
# >>> START function03 !
# >>> B
# >>> A
# >>> C
# >>> B
# >>> A
# >>> C
# >>> B
# >>> A
# >>> C
# >>> B
# >>> A
# >>> C
# >>> B
# >>> FINISH function02 !
# >>> A
# >>> FINISH function01 !
# >>> C
# >>> FINISH function03 !