美文网首页
threading.Thread实践

threading.Thread实践

作者: Mikasa___ | 来源:发表于2020-05-16 21:37 被阅读0次
    class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
    

    线程的参数传递:混合使用元组和字典 threading.Thread(target=方法名,args=(参数1, 参数2, ...), kwargs={"参数名": 参数1,"参数名": 参数2, ...})

    例如:threading.Thread(target=song,args=(1,),kwargs={"c":3,"b":2}).start()

    实验不同的参数传递方式,实践场景是多线程开启多个schedule
    Python中使用线程有两种方式:函数或者用类来包装线程对象。两种方式分别如下

    import schedule
    import os
    import datetime
    import subprocess
    import threading
    
    # 方法里执行command命令
    def job_fun(command):
        subprocess.run(command)
    
    # job 去做的事是开启线程,每个job 即每个线程下传参,传参是线程调的方法和参数
    def job(job_func, command):
        #这里传参只传了target,且函数后直接(参数)
        t = threading.Thread(target=job_func(command))
        t.start()
    #线程启动活动后的方法
    def run():
        schedule.every(1).seconds.do(job, job_fun, "python tasks/1.py")
        schedule.every(1).seconds.do(job, job_fun, "python tasks/2.py")
    while 1:
        run()
        schedule.run_pending()
    

    这种传递方式,运行起来也没问题

    file1start 2020-05-04 13:37:21.344153
    file1end 2020-05-04 13:37:31.344536
    file2 2020-05-04 13:37:31.457617
    file1start 2020-05-04 13:37:32.418298
    file1end 2020-05-04 13:37:42.418716
    file2 2020-05-04 13:37:42.501773
    file1start 2020-05-04 13:37:43.488669
    

    另一种参数传递方式:

    import schedule
    import os
    import datetime
    import subprocess
    import threading
    
    # 方法里执行command命令
    def job_fun(command):
        subprocess.run(command)
    
    # job 去做的事是开启线程,每个job 即每个线程下传参,传参是线程调的方法名,参数
    def job(job_func, command):
    
        t = My_thread(job_func, command)
        t.start()
    #用类包装线程对象
    class My_thread(threading.Thread):
        def __init__(self,func,command):
            super().__init__()
            self.func = func
            self.command = command
    #相当于线程启动后运行方法func(command)
        def run(self):
            self.func(self.command)
    #上面的合起来传参方式类似于threading.Thread(func,command)
    def each():
        schedule.every(1).seconds.do(job, job_fun, "python tasks/1.py")
        schedule.every(1).seconds.do(job, job_fun, "python tasks/2.py")
    
    while 1:
        each()
        schedule.run_pending()
    

    这种方式运行起来也没有问题

    file2 2020-05-04 17:52:42.780597
    file2 2020-05-04 17:52:43.781734
    file2 2020-05-04 17:52:43.781734
    file1start 2020-05-04 17:52:43.797361
    file1start 2020-05-04 17:52:43.797361
    file2 2020-05-04 17:52:43.812986
    file1start 2020-05-04 17:52:43.844236
    file1start 2020-05-04 17:52:44.788190
    file2 2020-05-04 17:52:44.794195
    file1start 2020-05-04 17:52:44.830220
    file2 2020-05-04 17:52:44.830220
    file2 2020-05-04 17:52:44.846728
    

    即threading.Thread(target=job_func(command))和threading.Thread(func,command)都可以的

    相关文章

      网友评论

          本文标题:threading.Thread实践

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