一、threading模块介绍
multiprocess模块的完全模仿了threading模块的接口,二者在使用层面,有很大的相似性,因而不再详细介绍
二、开启线程的两种方式
方式一:
from threading import Thread
import time
import random
def task(name):
print(‘%s is running‘ %name)
time.sleep(random.randint(1,3))
print(‘%s is end‘ %name)
#注意:在windows中Process()必须放到# if __name__ == ‘__main__‘:下
if __name__ == ‘__main__‘:
t1=Thread(target=task,args=(‘ALex‘,))
t1.start()
print(‘主函数‘)
#linux下的就不需要if __name__ == ‘__main__‘:
t1=Thread(target=task,args=(‘renwu1‘,))
t1.start()
print(‘主函数‘)
方式二:
from threading import Thread
import time
import random
class task(Thread):
def __init__(self,name):
super().__init__()
self.name=name
def run(self):
print(‘%s is runnging‘ %self.name)
time.sleep(random.randint(1,3))
print(‘%s is end‘ %self.name)
t1=task(‘renwu1‘)
t1.start()
print(‘主函数‘)
三、在一个进程下开启多个线程与在一个进程下开启多个子进程的区别
1、比较谁的开启速度快
from threading import Thread
from multiprocessing import Process
def task():
print(‘hello‘)
t1=Thread(target=task)
t1.start()
print(‘主函数/线程‘)
p1=Process(target=task)
p1.start()
print(‘主函数/进程‘)
2、查看pid
from threading import Thread
from multiprocessing import Process
import os
def task():
print(‘hello‘, os.getpid())
# 在主进程下开多个线程,每个线程都跟主进程的pid一样
t1=Thread(target=task)
t2=Thread(target=task)
t1.start()
t2.start()
print(‘主函数pid/线程‘,os.getpid())
# 在主进程下开多个进程,每个进程都有不同的pid
p1=Process(target=task)
p2=Process(target=task)
p1.start()
p2.start()
print(‘主函数pid/进程‘,os.getpid())
3、同一进程内的线程共享改进程内的数据
from threading import Thread
from multiprocessing import Process
def task():
global n
n=0
n=1
p=Process(target=task)
p.start()
p.join()
print(‘主函数/进程‘,n)
t=Thread(target=task)
t.start()
t.join()
原文地址:http://blog.51cto.com/10630401/2073045