美文网首页
守护线程/线程互斥锁

守护线程/线程互斥锁

作者: knot98 | 来源:发表于2018-09-06 15:00 被阅读0次

    守护线程

    from threading import Thread
    from multiprocessing import Process
    import time
    def foo():
        print(123)
        time.sleep(1)
        print("end123")
    
    def bar():
        print(456)
        time.sleep(3)
        print("end456")
    
    if __name__ == '__main__':
        # t1=Thread(target=foo)
        # t2=Thread(target=bar)
    
        t1=Process(target=foo)
        t2=Process(target=bar)
        t1.daemon=True
        t1.start()
        t2.start()
        print("main-------")
    

    线程互斥锁

    from threading import Thread,Lock
    import time
    
    mutex=Lock()
    n=100
    def task():
        global n
        mutex.acquire()
        temp=n
        time.sleep(0.1)
        n=temp-1
        mutex.release()
    
    if __name__ == '__main__':
        t_l=[]
        for i in range(100):
            t=Thread(target=task)
            t_l.append(t)
            t.start()
    
        for t in t_l:
            t.join()
        print(n)
    

    相关文章

      网友评论

          本文标题:守护线程/线程互斥锁

          本文链接:https://www.haomeiwen.com/subject/knjxgftx.html