编程语言
首页 > 编程语言> > Python3 多线程与互斥锁

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()

 

标签:__,threading,dance,t2,t1,互斥,sing,多线程,Python3
来源: https://www.cnblogs.com/xlcm/p/14849592.html