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

 

posted @ 2017-12-21 18:17  超龄码农  阅读(123)  评论(0编辑  收藏  举报