在python中创建线程

2024-09-24 02:27:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本,我希望一个函数和另一个同时运行。

我看过的示例代码:

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'

Tags: 函数import脚本defmyclasshelpthreadstart
3条回答

您的代码有一些问题:

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, ())

用于thread.start_new_thread的文档

您不需要使用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")

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

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

相关问题 更多 >