python锁

import threading
#定义全局变量
g_num = 0


def test1(num):
    global g_num
    for i in range(num):
        # 如果没上锁,则上锁,如果已有锁,堵塞
        mutex.acquire()
        g_num += 1
        mutex.release()
    print("---------in test1 g_num=%d--------" % g_num)

def test2(num):
     global g_num
     for i in range(num):
         mutex.acquire()
         g_num += 1
         mutex.release()
     print("---------in test2 g_num=%d--------" % g_num)


def main():
    t1 = threading.Thread(target=test1,args=(1000000,))
    t2 = threading.Thread(target=test2,args=(1000000,))

    t1.start()
    t2.start()
mutex = threading.Lock()

if __name__ == '__main__':
    main()

你可能感兴趣的:(python锁)