Python multithreading

김지수·2021년 4월 7일
1

OS&Network

목록 보기
3/3
post-thumbnail

코드1(스레드 1개)

from threading import Thread
import time

start_time = time.time()

def work(id, start, end, result):
    total = 0
    for i in range(start, end):
        total += i
    result.append(total)
    return

if __name__ == "__main__":
    START, END = 0, 100000000
    result = list()
    th1 = Thread(target=work, args=(1, START, END, result))

    th1.start()
    th1.join()

print("--- time %s seconds ---" % (time.time() - start_time))
print(f"Result: {sum(result)}")

# --- time 4.46619987487793 seconds ---
# Result: 4999999950000000

코드1(스레드 2개)

from threading import Thread
import time

start_time = time.time()

def work(id, start, end, result):
    total = 0
    for i in range(start, end):
        total += i
    result.append(total)
    return

if __name__ == "__main__":
    START, END = 0, 100000000
    result = list()
    th1 = Thread(target=work, args=(1, START, END//2, result))
    th2 = Thread(target=work, args=(2, END//2, END, result))

    th1.start()
    th2.start()
    th1.join()
    th2.join()

print("--- time %s seconds ---" % (time.time() - start_time))
print(f"Result: {sum(result)}")

# --- time 4.254441976547241 seconds ---
# Result: 4999999950000000

비교 코드

import time

start_time = time.time()
total = 0
for i in range(0, 100000000):
    total += i

print("--- time %s seconds ---" % (time.time() - start_time))
print(f"Result: {total}")
# print(total)

# --- time 8.859218835830688 seconds ---
# Result: 4999999950000000

결과

thread 1개thread 2개multithread X
4.46619987487793 seconds4.254441976547241 seconds8.859218835830688 seconds

설명

threading.Thread() 메소드

if __name__ == "__main__":
    START, END = 0, 100000000
    result = list()
    th1 = Thread(target=work, args=(1, START, END, result))
    th1.start()
    th1.join()

*if name == 'main': 안에서 실행해야 함.


thread 객체 생성

Thread(target=work, args=(arg, [[[args], args], ...])

parameterDescription
target스레드가 실행할 함수
args함수의 인자들

thread 시작

th1.start()


thread 실행이 완료될 때까지 기다림

th1.join()

profile
A Data human as a Learner, a Supporter, and a Listener

0개의 댓글