当前位置:
首页 > 编程开发 > Python基础教程 >
-
python基础教程之Python—创建进程的三种方式(2)
方式二:multiprocessing.Process()
- 子进程执行的函数结束,子进程就结束了。父进程等待子进程结束后才退出。
- 子进程修改全局变量或者局部变量,对父进程没有丝毫影响。
- 父进程执行完不退出,子进程会继续执行。父进程等待子进程结束后才退出。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
# --coding:utf8-- from multiprocessing import Process import os,time,random def test(num, msg): print "---子进程的pid=%d, ppid=%d, num=%d, msg=%s" % (os.getpid(), os.getppid(), num, msg) for i in range (random.randint( 1 , 5 )): print ( "----%d---" % i) time.sleep( 1 ) # p = Process(target=test, args=(), kwargs={}) # 当函数没有参数时候,可以这样写 p = Process(target = test, args = ( 100 ,), kwargs = { "msg" : "hello" }) p.start() # 让这个进程开始执行test函数里的代码 p.join() # 堵塞,可以加参数p.join(1)。等到p这个对象标记的进程结束之后,才会继续向下走 print "---父进程的pid=%d" % os.getpid() |
方式三:继承multiprocessing.Process类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
from multiprocessing import Process import os, time # 自定义的进程类 class MyProcess(Process): def __init__( self , value): self .value = value Process.__init__( self ) # super(MyProcess,self).__init__() # 在自定义的进程类中重写父类(Process)的run()方法 def run( self ): print "---子进程:%s开始执行,父进程pid:%s" % (os.getpid(),os.getppid()) while True : print ( "---传的参数值为:%d---" % self .value) time.sleep( 1 ) if __name__ = = '__main__' : p = MyProcess( 3 ) p.start() p.join( 6 ) # 阻塞等到子进程执行结束,超时时间为6秒。不加参数,会一直阻塞等待下去。 while True : print "---main---" time.sleep( 1 ) |
栏目列表
最新更新
python基础(27):类成员的修饰符、类的特殊
Python—创建进程的三种方式
Python openpyxl Excel绘制柱形图
Python学习笔记(九)
python基础-面向过程编程
Scrapy_redis主机连接虚拟机的数据库时显示
Scrapy对接Selenium
RabbitMQ消息队列
用python实现对元素的长截图
Python转义字符
.Net Standard(.Net Core)实现获取配置信息
Linux PXE + Kickstart 自动装机
Shell 编程 基础
Shell 编程 条件语句
CentOS8-网卡配置及详解
Linux中LVM逻辑卷管理
1.数码相框-相框框架分析(1)
Ubuntu armhf 版本国内源
Linux中raid磁盘阵列
搭建简易网站
mysql 安装了最新版本8.x版本后的报错:
Mysql空间数据&空间索引(spatial)
如何远程连接SQL Server数据库的图文教程
复制SqlServer数据库的方法
搜索sql语句
sql中返回参数的值
sql中生成查询的模糊匹配字符串
数据定义功能
数据操作功能
将Session值储存于SQL Server中