我有一个脚本,我想让一个函数与另一个同时运行。

我看过的示例代码:

import threading

def MyThread (threading.thread):
    # doing something........

def MyThread2 (threading.thread):
    # doing something........

MyThread().start()
MyThread2().start()

我在这方面遇到了麻烦。我更喜欢使用线程函数而不是类来实现这一点。

这是工作脚本:

from threading import Thread

class 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'

当前回答

你的代码有几个问题:

def MyThread ( threading.thread ):

你不能子类化一个函数;只有在课堂上 如果你要使用子类,你需要线程化。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

其他回答

使用线程实现多线程进程的简单方法

相同的代码片段

import threading

#function which takes some time to process 
def say(i):
    time.sleep(1)
    print(i)

threads = []
for i in range(10):
    
    thread = threading.Thread(target=say, args=(i,))

    thread.start()
    threads.append(thread)

#wait for all threads to complete before main program exits 
for thread in threads:
    thread.join()

你的代码有几个问题:

def MyThread ( threading.thread ):

你不能子类化一个函数;只有在课堂上 如果你要使用子类,你需要线程化。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

你可以在Thread构造函数中使用target参数直接传入一个被调用的函数,而不是run。

我尝试添加另一个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()

你重写run()方法了吗?如果你重写了__init__,你是否确保调用了基本线程threading.Thread.__init__()?

在启动两个线程之后,主线程是否继续在子线程上无限地/阻塞/连接工作,以便在子线程完成任务之前主线程的执行不会结束?

最后,是否有任何未处理的异常?