• python3之线程


    1线程的创建:

    import threading
    import time,random
    
    
    def text1():
        while True:
            print(1111111)
            time.sleep(random.random()*2)
    
    def text2():
        while True:
            print(2222222)
            time.sleep(random.random() * 2)
    def main():
        # text1()
        # text2()
    
        #创建多线程
        t1 = threading.Thread(target=text1)
        t2 = threading.Thread(target=text2)
        t1.start()  #执行多线程
        t2.start()
    
    if __name__ == "__main__":
        main()
    

     2互斥锁:

    在多线程之中全局变量是共享的;在执行过程中又可能会发生资源竞争,所以会用到互斥锁:比如

    import threading
    import time,os,random
    
    num = 0
    def text1(agr):
        global num
        for i in range(agr):
            num += 1
        print(num)
    
    def text2(agr):
        global num
        for i in range(agr):
            num += 1
        print(num)
    
    
    def main():
    
        t1 = threading.Thread(target=text1,args=(1000000,))
        t2 = threading.Thread(target=text2,args=(1000000,))
        t1.start()
        t2.start()
    
        time.sleep(5)
        print(num)
    
    if __name__ == "__main__":
        main()
    

     执行结果:如下,而不是我们向看到的2000000

    1170362
    1302259
    1302259
    

     如何解决呢,用到互斥锁:

    import threading
    import time,os,random
    
    num = 0
    def text1(agr,mutex):
        global num
        for i in range(agr):
            mutex.acquire()  #上锁
            num += 1
            mutex.release()  #解锁
        print(num)
    
    def text2(agr,mutex):
        global num
        for i in range(agr):
            mutex.acquire()  #上锁
            num += 1
            mutex.release() #解锁
    
        print(num)
    
    
    def main():
        mutex = threading.Lock()  #创建一个互斥锁
        t1 = threading.Thread(target=text1,args=(1000000,mutex))
        t2 = threading.Thread(target=text2,args=(1000000,mutex))
        t1.start()
        t2.start()
    
        time.sleep(5)
        print(num)
    
    if __name__ == "__main__":
        main()
    

     结果:

    1846157
    2000000
    2000000
    
  • 相关阅读:
    C++互斥器:Semaphores
    C++互斥器:Mutex
    内联函数(inline)
    C++显式转换
    线程同步控制
    拷贝构造函数——防篡改
    extern关键字
    虚析构、纯虚析构
    类的友元关系
    char 与 unsigned char的本质区别
  • 原文地址:https://www.cnblogs.com/yan-peng/p/9972606.html
Copyright © 2020-2023  润新知