zoukankan      html  css  js  c++  java
  • Python 35 线程(2)线程特性、守护线程、线程互斥锁

    一:线程特性介绍

    from threading import Thread
    import time
    
    n=100
    def task():
        global n
        n=0
    
    if __name__ == '__main__':
        t=Thread(target=task)
        t.start()
        t.join()
        print('',n)
    
    
    from threading import Thread
    import time,os
    
    def task():
        print('%s is running' %os.getpid())
    
    if __name__ == '__main__':
        t=Thread(target=task)
        t.start()
        print('',os.getpid())
    View Code
    from threading import Thread,active_count,current_thread
    import time,os
    
    def task():
        print('%s is running' %current_thread().name)
        time.sleep(2)
    
    if __name__ == '__main__':
        t=Thread(target=task,)
        t.start()
        # t.join()
        # print('主',active_count())
        print('',current_thread().name)
    View Code

    二:守护线程

    from threading import Thread
    import time
    
    def task(name):
        print('%s is running' %name)
        time.sleep(2)
        print('%s is done' %name)
    
    if __name__ == '__main__':
        t=Thread(target=task,args=('线程1',))
        t.daemon=True
        t.start()
        print('')
    View Code
    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-------")
    View Code

    三:线程互斥锁

    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)
    View Code
  • 相关阅读:
    技术问答集录(二)(RPC和MVC框架&syn,lock区别)
    Zookeeper同一台机器集群部署
    Linux——JDK安装
    VirtualBox CentOs7 设置ssh连接

    ThreadLocal
    关于Centos 7上面的防火墙配置
    windows下使用命令行关闭进程
    强类型 弱类型语言 静态 动态语言
    无法启动此程序 ,因为计算机中丢失MSVCP120.dll
  • 原文地址:https://www.cnblogs.com/zedong/p/9599454.html
Copyright © 2011-2022 走看看