码迷,mamicode.com
首页 > 编程语言 > 详细

python多进程和多线程---(自学中,坚持更新)

时间:2017-07-16 10:10:29      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:nbsp   多进程   name   坚持   语言   独立   coding   span   current   

首先我们知道进程和线程最明显的区别是:

多进程环境中,每个进程有自己的进程数据,各个进程数据之间是相互独立的。一个进程可以有多个线程,多个线程共享该进程的数据。

 

#-*- coding:utf-8 -*-

import os

from nt import getpid

 

print("current id: %d" %getpid())

输出

current id: 17452

 

创建进程:

创建进程,linux下用fork,和linux环境下C编程的fork函数一样,对于父进程而言,返回的是子进程的pid,对于子进程而言,返回的是0

from os import *

 

print("current id: %d" %getpid())

 

pid = fork()

if pid == 0:

    print("i am the child process:%d"  %getpid())

else:

print("i am parent process, my pid is %d, child process %d" %getpid(), pid)

 

python是个夸平台的语言,因此在windows下,python的multiprocessing模块可以实现多进程编程。

下面是个简单的例子

from multiprocessing import Process

from nt import getpid

 

 

def my_proc():

    print(‘i am the proc, pid(%d)‘ %getpid())

 

if __name__==‘__main__‘:

    print(‘Parent process %s.‘ %getpid())

   

    p = Process(target=my_proc)

    print(‘Process will start.‘)

    p.start()

    p.join()

    print(‘Process end.‘)

python多进程和多线程---(自学中,坚持更新)

标签:nbsp   多进程   name   坚持   语言   独立   coding   span   current   

原文地址:http://www.cnblogs.com/real-madrid/p/7189450.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!