Last active
December 20, 2018 14:38
-
-
Save staticor/3b646a15484adc0fd1f9d1242dd5e97d to your computer and use it in GitHub Desktop.
two thread work at same time, and output missy.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import threading | |
def job1(): | |
global A | |
for i in range(10): | |
A+=1 | |
print('job1',A) | |
def job2(): | |
global A | |
for i in range(10): | |
A+=10 | |
print('job2',A) | |
if __name__== '__main__': | |
lock=threading.Lock() | |
A=0 | |
t1=threading.Thread(target=job1) | |
t2=threading.Thread(target=job2) | |
t1.start() | |
t2.start() | |
t1.join() | |
t2.join() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# with lock | |
def job1(): | |
global A,lock | |
lock.acquire() | |
for i in range(10): | |
A+=1 | |
print('job1',A) | |
lock.release() | |
def job2(): | |
global A,lock | |
lock.acquire() | |
for i in range(10): | |
A+=10 | |
print('job2',A) | |
lock.release() | |
if __name__== '__main__': | |
lock=threading.Lock() | |
A=0 | |
t1=threading.Thread(target=job1) | |
t2=threading.Thread(target=job2) | |
t1.start() | |
t2.start() | |
t1.join() | |
t2.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment