为了账号安全,请及时绑定邮箱和手机立即绑定

在python中创建线程

在python中创建线程

梦里花落0921 2019-09-20 16:30:41
我有一个脚本,我想要一个功能与另一个同时运行。我看过的示例代码:import threadingdef MyThread (threading.thread):    # doing something........def MyThread2 (threading.thread):    # doing something........MyThread().start()MyThread2().start()我无法正常工作。我宁愿使用线程函数而不是类来实现。这是工作脚本:from threading import Threadclass myClass():    def help(self):        os.system('./ssh.py')    def nope(self):        a = [1,2,3,4,5,6,67,78]        for i in a:            print i            sleep(1)if __name__ == "__main__":    Yep = myClass()    thread = Thread(target = Yep.help)    thread2 = Thread(target = Yep.nope)    thread.start()    thread2.start()    thread.join()    print 'Finished'
查看完整描述

3 回答

?
MM们

TA贡献1886条经验 获得超2个赞

您不需要使用子类Thread来完成这项工作 - 看看我在下面发布的简单示例,看看如何:


from threading import Thread

from time import sleep


def threaded_function(arg):

    for i in range(arg):

        print("running")

        sleep(1)



if __name__ == "__main__":

    thread = Thread(target = threaded_function, args = (10, ))

    thread.start()

    thread.join()

    print("thread finished...exiting")

这里我展示了如何使用线程模块创建一个调用普通函数作为其目标的线程。你可以看到我如何在线程构造函数中传递我需要的任何参数。


查看完整回答
反对 回复 2019-09-20
?
FFIVE

TA贡献1797条经验 获得超6个赞

您的代码存在一些问题:


def MyThread ( threading.thread ):

你不能用函数子类化; 只有一堂课

如果您打算使用子类,则需要threading.Thread,而不是threading.thread

如果你真的只想用函数做这个,你有两个选择:


使用线程:


import threading

def MyThread1():

    pass

def MyThread2():

    pass


t1 = threading.Thread(target=MyThread1, args=[])

t2 = threading.Thread(target=MyThread2, args=[])

t1.start()

t2.start()

有线程:


import thread

def MyThread1():

    pass

def MyThread2():

    pass


thread.start_new_thread(MyThread1, ())

thread.start_new_thread(MyThread2, ())

doc for thread.start_new_thread


查看完整回答
反对 回复 2019-09-20
?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

我试图添加另一个join(),它似乎工作。这是代码


from threading import Thread

from time import sleep


def function01(arg,name):

for i in range(arg):

    print(name,'i---->',i,'\n')

    print (name,"arg---->",arg,'\n')

    sleep(1)



def test01():

    thread1 = Thread(target = function01, args = (10,'thread1', ))

    thread1.start()

    thread2 = Thread(target = function01, args = (10,'thread2', ))

    thread2.start()

    thread1.join()

    thread2.join()

    print ("thread finished...exiting")




test01()


查看完整回答
反对 回复 2019-09-20
  • 3 回答
  • 0 关注
  • 358 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信