■ Lock 클래스의 acquire/release 메소드를 사용하는 방법을 보여준다. ▶ 예제 코드 (PY)
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 31 32 33 34 35 36 37 38 39 40 41 42 43
|
import threading import time count = 10 lock = threading.Lock() class Developer(threading.Thread): def __init__(self, name): threading.Thread.__init__(self) self.name = name self.fixed = 0 def run(self): global count while True: lock.acquire() if count > 0: count -= 1 lock.release() self.fixed += 1 time.sleep(0.1) else: lock.release() break developerList = [] for name in ["스레드1", "스레드2", "스레드3"]: devloper = Developer(name) developerList.append(devloper) devloper.start() for devloper in developerList: devloper.join() print(devloper.name, "fixed", devloper.fixed) """ 스레드1 fixed 3 스레드2 fixed 4 스레드3 fixed 3 """ |
■ Thread 클래스를 사용해 스레드 상속을 구현하는 방법을 보여준다. ▶ 예제 코드 (PY)
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
import threading import time class TestThread(threading.Thread): def __init__(self, message): threading.Thread.__init__(self) self.message = message self.daemon = True self.event = threading.Event() def run(self): while True: if self.event.is_set(): break; time.sleep(1) print(self.message) threadList = [] for message in ["you", "need", "python"]: thread = TestThread(message) threadList.append(thread) thread.start() for i in range(10): time.sleep(1) print(i) for thread in threadList: thread.event.set() time.sleep(1) """ python need you 0 1 python you need 2 need python you you 3 python need python you need 4 need you 5 python you need 6 python need 7 you python 8 need you python 9 need you python """ |
■ Thread 클래스에서 스레드를 사용하는 방법을 보여준다. ▶ 예제 코드 (PY)
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
import threading import time def say(message, event): while True: if event.is_set(): break time.sleep(1) print(message) eventList = [] for message in ["you", "need", "python"]: event = threading.Event() thread = threading.Thread(target = say, args = (message, event)) thread.daemon = True eventList.append(event) thread.start() for i in range(10): time.sleep(1) print(i) for event in eventList: event.set() time.sleep(1) """ you need python 0 python 1 you need need python you 2 python need you 3 need 4 python you you 5 need python need you 6 python need python 7 you python 8 need you need python you 9 python need you """ |