반응형
간단한 파이썬 멀티쓰레딩 예제들
예제 #01
1
2
3
4
5
6
7
|
import threading
def helloworld():
print("Hello World!")
t1 = threading.Thread(target=helloworld)
t1.start()
|
cs |
예제 #02
1
2
3
4
5
6
7
8
9
10
11
12
13
|
# import threading
def function1():
for x in range(10000):
print("1")
def function2():
for x in range(10000):
print("2")
function1();
function2();
|
cs |
(threading을 적용하지 않았을 때)
예제 #03
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import threading
def function1():
for x in range(10000):
print("1")
def function2():
for x in range(10000):
print("2")
t1 = threading.Thread(target=function1)
t2 = threading.Thread(target=function2)
t1.start()
t2.start()
|
cs |
예제 #04
1
2
3
4
5
6
7
8
9
10
|
import threading
def hello():
for x in range(50):
print("Hello")
t1 = threading.Thread(target=hello)
t1.start()
print("Another Text")
|
cs |
("Another Text"가 먼저 출력되고 Thread가 실행됨)
예제 #05
1
2
3
4
5
6
7
8
9
10
11
12
|
import threading
def hello():
for x in range(50):
print("Hello")
t1 = threading.Thread(target=hello)
t1.start()
t1.join()
print("Another Text")
|
cs |
(Thread가 전부 실행된 이후에 "Another Text"가 출력됨)
예제 #06
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
|
import threading
import time
class ThreadCounter:
def __init__(self):
self.counter = 0
self.lock = threading.Lock()
def count(self, thread_no):
while True:
# LOCKING
self.lock.acquire()
self.counter += 1
print(f"{thread_no}: Just increased counter to {self.counter}")
time.sleep(1) # WORK WE ARE DOING
print(f"{thread_no}: Done some work, now value is {self.counter}")
self.lock.release()
tc = ThreadCounter()
for i in range(30):
t = threading.Thread(target=tc.count, args=(i, ))
t.start()
|
cs |
(Locking and Synchronizing Threads without sleep)
예제 #07
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
|
import threading
import time
class ThreadCounter:
def __init__(self):
self.counter = 0
self.lock = threading.Lock()
def count(self, thread_no):
while True:
# LOCKING
self.lock.acquire()
self.counter += 1
print(f"{thread_no}: Just increased counter to {self.counter}")
time.sleep(1) # WORK WE ARE DOING
print(f"{thread_no}: Done some work, now value is {self.counter}")
self.lock.release()
time.sleep(random.randint(1, 3))
tc = ThreadCounter()
for i in range(30):
t = threading.Thread(target=tc.count, args=(i, ))
t.start()
|
cs |
(Locking and Synchronizing Threads with sleep)
반응형
'공부 > 파이썬 Python' 카테고리의 다른 글
[Python] 언제 은퇴할 수 있을까를 계산 (0) | 2022.03.27 |
---|---|
블록체인의 기본 원리: 투명성(Transparency) with Python (0) | 2022.03.26 |
Python을 사용한 유방암 검출 튜토리얼 (Breast Cancer Detection with Python) (1) | 2022.03.23 |
Python에서의 실제 콜센터 프로세스 시뮬레이션 (0) | 2022.03.23 |
Python으로 전처리 파이프라인 설계하기 (3) | 2022.03.22 |
댓글