一、依赖的三方库
????????线程库: threading
? ? ? ? 进程库: multiprocessing
二、多线程
import threading
from time import sleep
def song(num):
for i in range(num):
print('{:*^30}'.format('唱歌'))
sleep(1)
def dance(num):
for i in range(num):
print('{:-^30}'.format('跳舞'))
sleep(1)
def main():
#实例化两个线程,并启动
#target指向函数,args后面跟元组格式的参数,当作实际参数传入函数中
threading.Thread(target=song,args=(5,)).start()
threading.Thread(target=dance,args=(5,)).start()
#打印线程数
print(threading.enumerate())
if __name__ =='__main__':
main()
三、多进程
import threading,multiprocessing
from time import sleep
def song(num):
for i in range(num):
print('{:*^30}'.format('唱歌'))
sleep(1)
def dance(num):
for i in range(num):
print('{:-^30}'.format('跳舞'))
sleep(1)
def main():
#实例化两个进程,并启动
#target指向函数,args后面跟元组格式的参数,当作实际参数传入函数中
multiprocessing.Process(target=song,args=(5,)).start()
multiprocessing.Process(target=dance, args=(5,)).start()
if __name__ =='__main__':
main()
|