简单创建线程:
通过threading.Thread来创建线程。
thd = threading.Thread(target=hello)
上行代码创造出了一个线程。该线程可实现输出hello world语句三遍的功能。
thd.start() #开始线程
import threading
import time
def hello():
for i in range(3):
print('hello world……%d'%i)
time.sleep(1)
if __name__ == '__main__':
thd = threading.Thread(target=hello)
thd.start()
hello world……0
hello world……1
hello world……2
另一个创建线程的方法是使用run方法。
import threading
import time
def hello():
for i in range(3):
print('hello world……%d'%i)
time.sleep(1)
class THD(threading.Thread):
def run(self):
for i in range(3):
print('hello world……%d' % i)
time.sleep(1)
if __name__ == '__main__':
thd = THD()
thd.start()
以上创建的都为子线程,因为主线程就是程序本身,程序运行完毕,主线程结束。
创建进程:
和创建线程类似,用multiprocessing.Process来创建。
import time
import multiprocessing
def hello():
for i in range(3):
print('hello world……%d'%i)
time.sleep(1)
if __name__ == '__main__':
por = multiprocessing.Process(target=hello)
por.start()
hello world……0
hello world……1
hello world……2