python3学习笔记(三)多线程与多进程

线程thread,库threading

进程process,库Process

使用起来方法跟其他语言相似,也不需要下载其他的库,语言自带的库里就有

1.多线程的例子

 1 #coding=utf-8
 2 import threading
 3 from time import sleep, ctime
 4 
 5 loops = [1, 2]
 6 
 7 def loop(nloop, nsec):
 8     print('start loop', nloop, 'at:', ctime())
 9     sleep(nsec)
10     print('loop', nloop, 'done at:', ctime())
11 
12 
13 
14 def main():
15     print('starting at:', ctime())
16     threads = []
17     nloops = range(len(loops))  # nloops=1,2
18 
19     for i in  nloops:
20         t = threading.Thread(target=loop, args=(i, loops[i]))
21         threads.append(t)
22 
23     for i in nloops:
24         threads[i].start()
25 
26     for i in nloops:
27         threads[i].join()
28 
29     print('all end', ctime())
30 
31 
32 if __name__ == '__main__':   #Make a script both importable and executable
33     main()
View Code

2.多进程的例子

 1 #coding=utf-8
 2 from multiprocessing import  Process
 3 import os
 4 
 5 def info(title):
 6     print(title)
 7     print('module name:', __name__)
 8     if hasattr(os, 'getppid'):
 9         print('parent process:', os.getppid())    #父进程id
10     print('process id:', os.getpid())    #进程自己的id
11 
12 
13 def f(name):
14     info('function f')
15     print('hello', name)
16 
17 #如果本进程A创建了一个进程B 那么B是A的子进程   A是B的父进程
18 if __name__ == '__main__':
19     info('main process')
20     p = Process(target=f, args=('ks', ))
21     p.start()
22     p.join()
View Code

 

转载于:https://www.cnblogs.com/ikel/p/8081898.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值