μ¬μ§ μΆμ²: https://solt.tistory.com/78
import threading
g_count = 0
def thread_main():
global g_count
for i in range(1000000):
g_count = g_count + 1
threads = []
lock = threading.Lock()
for i in range(50):
th = threading.Thread(target= thread_main)
threads.append(th)
for th in threads:
th.start()
for th in threads:
th.join()
print('g_count = ', g_count)
g_count
λΌλ μ μλ³μλ₯Ό μ μΈν΄μ£Όκ³ thread_main
)λ₯Ό μ μνλ€μ΄μ체μ κ° μ»¨ν μ€νΈ μ€μμΉμν΄μ λ°±λ§μ λ°λ³΅λ¬Έμ΄ μ€νλλ€κ° μ°λ λκ° μ€κ°μ λ°λμ΄μ μκΈ°λ μΌμ΄λ€.
import threading
g_count = 0
def thread_main():
global g_count
lock.acquire()
for i in range(1000000):
g_count = g_count + 1
lock.release()
threads = []
lock =
for i in range(50):
th = threading.Thread(target= thread_main)
threads.append(th)
for th in threads:
th.start()
for th in threads:
th.join()
print('g_count = ', g_count)
lock.acquire()λ₯Ό μ¬μ©ν΄μ μ€λ λκ° λμμ λ°λ³΅λ¬Έμ μ κ·Όν λ νκ°μ μ€λ λλ§ μ κ·Όνκ³ λλ¨Έμ§λ λͺ»μ κ·Όνκ² νλ€.
λ°λ³΅λ¬Έμ μ κ·Όν μ€λ λκ° λμ€λ©΄μ lock.release()ν¨μλ₯Ό μ€νν΄μ λ€μ μ€λ λκ° λ°λ³΅λ¬Έμ μ κ·Όν μ μκ² νλ€.
lock.acquire()
for i in range(1000000):
g_count = g_count + 1
lock.release()
g_count += 1
μ΄ μκ³μμ(critical resource)μ΄λ€. P(s): wait(S) {
while s <= 0 // λκΈ°
S--; // λ€λ₯Έ νλ‘μΈμ€ μ κ·Ό μ ν (1κ°μ)
}
V(S): signal(S) {
s ++; // λ€λ₯Έ νλ‘μΈμ€ μ κ·Ό νμ© (1μ¦κ°)
}
P(s): wait(S) {
while s <= 0 // λκΈ°
S--; // λ€λ₯Έ νλ‘μΈμ€ μ κ·Ό μ ν (1κ°μ)
}
wait(S) {
S->count--;
if (S->count <= 0) {
add this process to S->queue; // λκΈ°
block() // λΈλ‘, sleap()
}
}
signal(s) {
S->count++;
if (S->count >=1) {
remove a process P form S->queue;
wakeup(P) // κΉ¨μ°κΈ°
}
}