在Python中创建线程

14 浏览
0 Comments

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

admin 更改状态以发布 2023年5月25日
0
0 Comments

你的代码有几个问题:

def MyThread ( threading.thread ):

  • 你不能用函数来派生子类,只能用类来派生
  • 如果你要使用子类,你需要的是 threading.Thread,而不是 threading.thread

如果你真的想要只使用函数来做到这一点,你有两个选择:

使用 threading:

import threading
def MyThread1():
    pass
def MyThread2():
    pass
t1 = threading.Thread(target=MyThread1, args=[])
t2 = threading.Thread(target=MyThread2, args=[])
t1.start()
t2.start()

使用 thread:

import thread
def MyThread1():
    pass
def MyThread2():
    pass
thread.start_new_thread(MyThread1, ())
thread.start_new_thread(MyThread2, ())

针对 thread.start_new_thread 的文档

0
0 Comments

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

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

0