1.用进程实现类似定时器的功能
import multiprocessing import time def clock(interval): while True: print "The time is {0}".format(time.ctime()) time.sleep(interval) if __name__ == "__main__": p = multiprocessing.Process(target=clock,args=(3,)) p.start() p.join()
2.进程的基本编程
run:如果在创建Process对象的时候不指定target,那么就会默认执行Process的run方法: #encoding:utf-8 from multiprocessing import Process import os, time, random def r(): print ‘run method‘ if __name__ == "__main__": print "main process run..." #没有指定Process的targt p1 = Process() p2 = Process() #如果在创建Process时不指定target,那么执行时没有任何效果。因为默认的run方法是判断如果不指定target,那就什么都不做 #所以这里手动改变了run方法 p1.run = r p2.run = r p1.start() p2.start() p1.join() p2.join() print "main process runned all lines..."
最上面演示的代码中,在调用Process的start方法后,调用了两次join方法。这个join方法是干什么的呢? 官方文档的意思是:阻塞当前进程,直到调用join方法的那个进程执行完,再继续执行当前进程。 比如还是刚才的代码,只是把两个join注释掉了: #encoding:utf-8 from multiprocessing import Process import os, time, random def r1(process_name): for i in range(5): print process_name, os.getpid() #打印出当前进程的id time.sleep(random.random()) def r2(process_name): for i in range(5): print process_name, os.getpid() #打印出当前进程的id time.sleep(random.random()) if __name__ == "__main__": print "main process run..." p1 = Process(target=r1, args=(‘process_name1‘, )) p2 = Process(target=r2, args=(‘process_name2‘, )) p1.start() p2.start() #p1.join() #p2.join() print "main process runned all lines..."