Python3 多线程与互斥锁

简单实现多线程

import threading
import time

def sing(sing):
    for i in range(5):
        print("---sing()---{}".format(sing))
        time.sleep(1)

def dance(dance):
    for i in range(5):
        print("---dance()---{}".format(dance))
        time.sleep(1)

def main():
    t1 = threading.Thread(target=sing,args=("t1",))
    t2 = threading.Thread(target=dance,args=("t2",))
    t1.start()
    t2.start()

if __name__ == "__main__":
    main()

 多线程互斥锁

import threading
import time

A = 2
lock = threading.Lock()
#创建一个互斥锁

def sing(sing):
    global A
    for i in range(500000):
        lock.acquire()
        #加锁
        A += 1
        lock.release()
        #解锁
        print('{}:{}'.format(sing,i))

def dance(dance):
    global A
    for i in range(500000):
        lock.acquire()
        #加锁
        A -= 1
        lock.release()
        #解锁
        print('{}:{}'.format(dance,i))

def main():
    global A
    t1 = threading.Thread(target=sing,args=("t1",))
    t2 = threading.Thread(target=dance,args=("t2",))
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    print(A)

if __name__ == "__main__":
    main()

 

上一篇:python进程(1)简单使用


下一篇:多线程介绍