码迷,mamicode.com
首页 > 编程语言 > 详细

python并发编程之多线程编程

时间:2018-02-26 13:21:01      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:python线程编程

一、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()

python并发编程之多线程编程

标签:python线程编程

原文地址:http://blog.51cto.com/10630401/2073045

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!