python mutiprocessing 入门示例,,multiprocess
python mutiprocessing 入门示例,,multiprocess
multiprocessing:支持子进程、通信和共享数据、执行不同形式的同步。Process:创建进程的类:Process([group [, target [, name [, args [, kwargs]]]]]),target表示调用对象,args表示调用对象的位置参数元组。kwargs表示调用对象的字典。Name为别名。Group实质上不使用。方法有:is_alive()、.join([timeout])、run()、start()、terminate()。属性有:authkey、daemon(要通过start()设置)、exitcode(进程在运行时为None、如果为–N,表示被信号N结束)、name、pid。
Process类中,注意daemon是父进程终止后自动终止,且自己不能产生新进程,必须在start()之前设置。
创建函数并将其作为单个进程。
#!/usr/bin/pythonimport multiprocessingimport timedef clock(interval): while True: print("The time is {0}".format(time.ctime())) time.sleep(interval)if __name__ == '__main__': p = multiprocessing.Process(target=clock, args=(15,)) p.start()
将进程定义为类:
#!/usr/bin/pythonimport multiprocessingimport timeclass ClockProcess(multiprocessing.Process): def __init__(self,interval): multiprocessing.Process.__init__(self) self.interval = interval def run(self): while True: print("The time is {0}".format(time.ctime())) time.sleep(self.interval)if __name__ == "__main__": p = ClockProcess(15) p.start()
执行结果:
process startedThe time is Sun Dec 30 17:16:18 2012The time is Sun Dec 30 17:16:33 2012The time is Sun Dec 30 17:16:48 2012The time is Sun Dec 30 17:17:03 2012The time is Sun Dec 30 17:17:18 2012The time is Sun Dec 30 17:17:33 2012The time is Sun Dec 30 17:17:48 2012The time is Sun Dec 30 17:18:03 2012The time is Sun Dec 30 17:18:18 2012The time is Sun Dec 30 17:18:33 2012The time is Sun Dec 30 17:18:48 2012The time is Sun Dec 30 17:19:03 2012
为了兼容windows而这样创建类,而且还要注意,在windows下,要在命令行才能执行,用IDE是不行的。
相关内容
- Python 的多进程 fork,python进程fork,using_fork.p
- Python 多进程实现分析,python进程实现,Python Stand
- Python连接使用redis,python连接redis,需要下载 redis-p
- 使用python获得网站的alexa排名,pythonalexa,如下脚本,使
- python获得Google PageRank(PR)的脚本,pythonpagerank,如下p
- python 实现命令行的进度条,python进度条,如下代码片段
- python实现switch语句,pythonswitch语句,python本身没有sw
- python实现对象的深拷贝,python实现拷贝,python对象的深拷
- python的super关键字使用示例,pythonsuper关键字,super在单继
- os.rename()导致WindowsError: [Error 32]问题的解决,,刚接触
评论关闭