Python3 多线程与互斥锁

2021/6/5 20:51:05

本文主要是介绍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()

 



这篇关于Python3 多线程与互斥锁的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程