在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'
7 个回答
23
我试着加了另一个 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()
51
你的代码有几个问题:
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 的文档
418
你不需要使用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")
在这里,我展示了如何使用线程模块来创建一个线程,这个线程会调用一个普通的函数作为它的目标。你可以看到,我可以在创建线程的时候传递任何需要的参数给它。