代码:

import threading
import time


num = 0
mutex = threading.Lock()

def test1(cnt):
global num

for i in range(cnt):
mutex.acquire()
print("test1, before add num = %d--" % num)
num += 1
print("test1, after add num = %d--" % num)
print("------------------\r\n")
mutex.release()
time.sleep(0.001)


def test2(cnt):
global num

for i in range(cnt):
mutex.acquire()
print("test2, before add num = %d--" % num)
num += 1
print("test2, after add num = %d--" % num)
print("------------------\r\n")
mutex.release()
time.sleep(0.001)


if __name__ == "__main__":

print("--创建线程之前, num = %d--" % num)

t1 = threading.Thread(target=test1, args=(100000,))
t1.start()

t2 = threading.Thread(target=test2, args=(100000,))
t2.start()

while len(threading.enumerate()) != 1:
time.sleep(1)

print("最终结果为:num=%d" % num)

执行结果:

root@ubuntu:/tmp# python3 main.py
test1, before add num = 138694--
test1, after add num = 138695--
------------------

test2, before add num = 138695--
test2, after add num = 138696--
------------------

test1, before add num = 138696--
test1, after add num = 138697--
------------------

test2, before add num = 138697--
test2, after add num = 138698--
------------------

test1, before add num = 138698--
test1, after add num = 138699--
------------------

test2, before add num = 138699--
test2, after add num = 138700--
------------------

test1, before add num = 138700--
test1, after add num = 138701--
------------------

test2, before add num = 138701--
test2, after add num = 138702--
------------------

test1, before add num = 138702--
test1, after add num = 138703--
------------------

test2, before add num = 138703--
test2, after add num = 138704--
------------------

test1, before add num = 138704--
test1, after add num = 138705--
------------------
root@ubuntu:/tmp#