• 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
  • 相关阅读:
    xilinx下载器,JTAG-HS3和Platform Cable USB II 速度对比
    LATTICE下载器HW-USBN-2B使用说明
    altera下载器高速版本 PL-USB2-BLASTER 使用说明
    FPGA流程设计
    关于fpga的后仿真重要性
    使用MyBatis分页插件PageHelper遇到的问题
    java 面试题总结01
    netty Demo
    netty 概念篇
    pom.xml 简述
  • 原文地址:https://www.cnblogs.com/zedong/p/9599454.html
Copyright © 2020-2023  润新知