본문 바로가기
공부/파이썬 Python

간단한 파이썬 멀티쓰레딩 예제들

by 혼밥맨 2022. 3. 25.
반응형

간단한 파이썬 멀티쓰레딩 예제들

 

예제 #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(13))
 
tc = ThreadCounter()
 
 
for i in range(30):
    t = threading.Thread(target=tc.count, args=(i, ))
    t.start()
cs

(Locking and Synchronizing Threads with sleep)

반응형

댓글