python- multi-thread synchronization mutex is created to solve the problem of resource contention


Threading Import
Import Time

# define a global variable
g_num = 0


DEF test1 (NUM):
Global g_num
for I in (NUM) Range:
g_num + =. 1
Print ( 'test1 g_num in ------- = {}'. the format (g_num))


DEF test2 (NUM):
Global g_num
for I in Range (NUM):
g_num + =. 1
Print ( 'test1 g_num in ------- = {}' the format (g_num.))


DEF main ():
T1 = threading.Thread (target = test1, args = (1000000,)) # test results of ten thousand output is correct, but there is a problem with one million
t2 = threading.Thread (target = test1 , args = (1000000,))

t1.start ()
t2.start ()

# wait time implementation of the above two processes
the time.sleep (. 5)
Print ( '------- in the Thread main g_num = {} '.format (g_num))


__name__ == IF '__main__':
main ()

# The above procedure will cause resource contention problems, the results of the final output is (the result will be different each time, but certainly not our logic results)

-------in test1 g_num=1172278
-------in test1 g_num=1288801
-------in main Thread g_num=1288801

 

## solution is as follows (in red font for newly added code)

Threading Import 
Import Time

# define a global variable
g_num = 0


DEF test1 (NUM):
, Ltd. Free Join g_num

for i in (NUM) the Range:
# locked if you have not been locked, then unlocked at this time success
# If a previously locked is locked, then it will clog here until the lock is solved
mutex.acquire ()
g_num + =. 1
mutex.release ()
Print ( 'test1 g_num in ------- = {}'. the format (g_num))


DEF test2 (NUM):
Global g_num

for I in Range (NUM):
mutex.acquire ()
g_num + =. 1
mutex.release ()
Print ( 'test1 g_num in ------- = { .} 'the format (g_num))


# Create a mutex, the default is unlocked
the mutex of threading.Lock = ()


DEF main ():
t1 = threading.Thread (target = test1, args = (1000000,)) # test results of ten thousand output is correct, but there is a problem with one million
t2 = threading.Thread (target = test1, args = (1000000,))

t1.start ()
t2.start ()

# wait time implementation of the above two processes
the time.sleep (. 5)
Print ( '------- in the Thread main g_num = {}'. the format (g_num))


IF the __name__ == '__main__':
main ()

Guess you like

Origin www.cnblogs.com/fuyouqiang/p/11770443.html
Recommended