zoukankan      html  css  js  c++  java
  • Python多线程threading的使用

    一. threading的参数传递,参数之后的’,‘不能少,此处的’,‘是用来区分此参数作为元组(包含多个参数)来传递的,而不是单个参数传递

    #coding:utf-8
    import threading
    import time
    
    def b(arg):
        time.sleep(2)
        print("I'm B")
        print("I'm", threading.current_thread().name)
        print("I'm",arg)
        time.sleep(2)
        print("I'm sleep after")
    
    def a():
        print("I'm A")
        s = threading.Thread(target=b, name='LoopThread',args=("test",))
        s.start()
        print("I'm",threading.current_thread().name)
        #time.sleep(3)
        print("I'm C")
    
    print(a())

    二. sleep的位置很重要,如上输出结果:

    I'm A
    I'm MainThread
    I'm C
    None
    I'm B
    I'm LoopThread
    I'm test
    I'm sleep after

    第二种情况:

    #coding:utf-8
    import threading
    import time
    
    def b(arg):
        #time.sleep(2)
        print("I'm B")
        print("I'm", threading.current_thread().name)
        print("I'm",arg)
        time.sleep(2)
        print("I'm sleep after")
    
    def a():
        print("I'm A")
        s = threading.Thread(target=b, name='LoopThread',args=("test",))
        s.start()
        print("I'm",threading.current_thread().name)
        #time.sleep(3)
        print("I'm C")
    
    print(a())

    输出结果:

    I'm A
    I'm BI'm
    I'm  LoopThread
    I'm test
    MainThread
    I'm C
    None
    I'm sleep after

    第三种情况:

    #coding:utf-8
    import threading
    import time
    
    def b(arg):
        #time.sleep(2)
        print("I'm B")
        print("I'm", threading.current_thread().name)
        print("I'm",arg)
        time.sleep(2)
        print("I'm sleep after")
    
    def a():
        print("I'm A")
        s = threading.Thread(target=b, name='LoopThread',args=("test",))
        s.start()
        print("I'm",threading.current_thread().name)
        time.sleep(3)
        print("I'm C")
    
    print(a())

    输出结果:

    I'm A
    I'm BI'm
     MainThread
    I'm LoopThread
    I'm test
    I'm sleep after
    I'm C
    None

    似乎其中一个线程稍微阻塞(或睡眠)就会立马开始执行另外一个,可以据此调控两个线程的交替?

    关于线程的参数传递需要注意

  • 相关阅读:
    PowerShell尝试ssh登录
    PowerShell收发TCP消息包
    powershell对指定IP进行端口扫描
    PowerShell尝试登录ftp
    PowerShell批量扫描IP和端口
    《PowerShell 3.0 Advanced Admin handbook》已于今日上市
    PowerShell尝试登录SQL Server
    Docker 数据卷
    Dockerfile自定义镜像
    Docker 容器操作
  • 原文地址:https://www.cnblogs.com/sen-c7/p/9475245.html
Copyright © 2011-2022 走看看