多进程

在Unix/Linux下,为我们提供了类似c中<unistd.h>头文件里的的fork()函数的接口,这个函数位于os模块中,相同与c中类似,对于父进程fork()调用返回子进程ID,对于子进程返回0

import os, time

pid = os.fork()
if pid == 0:
while True:
print 'child process'
time.sleep(1)
else:
while True:
print 'parent process'
time.sleep(3)

考虑到Windows并没有这个调用,python为我们提供了跨平台的版本号。这就是multiprocessing模块。通过multiprocessing模块中的Process类可实现跨平台的多进程。使用方法很easy

#coding:utf-8
from multiprocessing import Process
import os, time def handler(args):
print 'process parameter is %s' % args
while True:
print 'child process'
time.sleep(1) if __name__=='__main__':
print 'parent process is %d' % os.getpid()
child_proc = Process(target = handler, args=('test parameter',)) #指定子进程開始运行的函数
child_proc.start()
while True:
print 'parent process'
time.sleep(3)

注意:若不加if __name__=='__main__'。子进程启动后会将模块内的代码再运行一遍。为避免不必要的错误,应该加上它

Python为了更方便的使用多进程还提供了进程池Pool, 位于multiprocessing模块中,进程池用于对于并发响应要求较高的条件中,预先分配进程,节省了处理过程中fork的开销

关于很多其它进程池的内容可參考 http://blog.csdn.net/aspnet_lyc/article/details/38946915#t3  中的TCP预先派生子进程server

#coding:utf-8
from multiprocessing import Pool
import os, time, random def handler(proc_args):
print proc_args if __name__ == '__main__':
pool = Pool(4) #设置进程池中的进程数
for loop in range(4):
pool.apply_async(handler, args=(loop,)) #apply_async(func,args),从进程池中取出一个进程运行func,args为func的參数。返回一个 AsyncResult的对象。对该对象调用get()方法能够获得结果。 pool.close() #不在往进程池中加入进程
pool.join() #等待全部子进程结束
print 'All child processes done'

多线程

Python中对于多线程提供了thread和threading模块, threading对thread进行了封装,更易用。python官网的描写叙述例如以下

This module provides low-level primitives for working with multiple threads (also called light-weight processes or tasks) — multiple threads of control sharing their global data space. For synchronization, simple locks (also called
mutexes or binary semaphores) are provided. The threading module provides an easier to use and higher-level threading API built on top of this module

调用thread模块中的start_new_thread()函数来产生新线程

import thread

def thread_handler(args):
print args if __name__ == '__main__':
thread.start_new_thread(thread_handler, ('test parameter',))
while True:
pass

将线程函数传入并创建Thread实例。然后调用start()创建线程并运行

import threading

def thread_handler(args):
print args if __name__ == '__main__':
th1 = threading.Thread(target=thread_handler, args=('test parameter 1',))
th2 = threading.Thread(target=thread_handler, args=('test parameter 2',))
th1.start()
th2.start()
th1.join()
th2.join()
print 'All threads ended'

python 并发编程入门的更多相关文章

  1. Python并发编程之深入理解yield from语法(八)

    大家好,并发编程 进入第八篇. 直到上一篇,我们终于迎来了Python并发编程中,最高级.最重要.当然也是最难的知识点--协程. 当你看到这一篇的时候,请确保你对生成器的知识,有一定的了解.当然不了解 ...

  2. Python并发编程__多进程

    Python并发编程_多进程 multiprocessing模块介绍 python中的多线程无法利用多核优势,如果想要充分地使用多核CPU的资源(os.cpu_count()查看),在python中大 ...

  3. Python并发编程的几篇文章

    Python几种并发实现方案的性能比较 http://www.elias.cn/Python/PyConcurrency?from=Develop.PyConcurrency python并发编程 h ...

  4. Python游戏编程入门

    <Python游戏编程入门>这些文章负责整理在这本书中的知识点.注意事项和课后习题的尝试实现.并且对每一个章节给出的最终实例进行分析和注释. 初识pygame:pie游戏pygame游戏库 ...

  5. 自学Python之路-Python并发编程+数据库+前端

    自学Python之路-Python并发编程+数据库+前端 自学Python之路[第一回]:1.11.2 1.3

  6. Python并发编程二(多线程、协程、IO模型)

    1.python并发编程之多线程(理论) 1.1线程概念 在传统操作系统中,每个进程有一个地址空间,而且默认就有一个控制线程 线程顾名思义,就是一条流水线工作的过程(流水线的工作需要电源,电源就相当于 ...

  7. Python并发编程一(多进程)

    1.背景知识(进程.多道技术) 顾名思义,进程即正在执行的一个过程.进程是对正在运行程序的一个抽象. 进程的概念起源于操作系统,是操作系统最核心的概念,也是操作系统提供的最古老也是最重要的抽象概念之一 ...

  8. 《转载》Python并发编程之线程池/进程池--concurrent.futures模块

    本文转载自Python并发编程之线程池/进程池--concurrent.futures模块 一.关于concurrent.futures模块 Python标准库为我们提供了threading和mult ...

  9. Python并发编程系列之多线程

    1 引言 上一篇博文详细总结了Python进程的用法,这一篇博文来所以说Python中线程的用法.实际上,程序的运行都是以线程为基本单位的,每一个进程中都至少有一个线程(主线程),线程又可以创建子线程 ...

随机推荐

  1. Build website project by roslyn through devenv.com

    1.fetch the source code2.compile controls project3.copy files under bin folder of controls to bin fo ...

  2. Linux学习之设置联网,关闭防火墙,关闭selinux

    桥接模式,给一台物理机,有自己独立的IP. boot分区,引导分区,系统启动,内核文件. swap分区,内存扩展分区.1.5或2倍.内存不够的时候,会写入其中.正常给8G或者16G就够了.不需要非要1 ...

  3. Wifi加密协议漏洞

    互联网,移动互联网,物联网给我们带来便利的同时,也更容易让我们被黑客攻击,安全问题也越来越突出重要.比如近些天出现的wpa2的漏洞,让广泛应用的Wifi处于危机状态,说不定哪天你身边黑客就利用它攻击获 ...

  4. H3C路由器查看序列号信息

    H3C MSR系列的路由器,查看本机的MAC地址.序列号信息和生产日期信息等可以使用dis device manuinfo 命令查看,以下是执行结果: slot 0 DEVICE_NAME       ...

  5. if,elif,else的关系 input print int的用法

    qian=input("找劳保网是什么网站?:")if qian=="zhaolaobaowang.com": print("正确")els ...

  6. HUdson2092整数解

    2019-05-17 16:04:37 加油,坚持就是胜利,fightting m / i的情况,i可能等于0 #include <bits/stdc++.h> using namespa ...

  7. Mybatis中resultMap的作用-解决实体类属性名和数据库字段不一致

    解决实体类属性名和数据库字段不一致

  8. 关于react-router-dom入门配置

    react-router-dom入门配置 配置 参考:github https://reacttraining.com/react-router/web/api/BrowserRouter 1. 导入 ...

  9. fullPage插件使用

    fullPage插件 fullPage.js 是一个基于 jQuery 的插件,它能够很方便.很轻松的制作出全屏网站,主要功能有: 支持鼠标滚动 支持前进后退和键盘控制 多个回调函数 支持手机.平板触 ...

  10. poj3083 Children of the Candy Corn 深搜+广搜

    这道题有深搜和广搜.深搜还有要求,靠左或靠右.下面以靠左为例,可以把简单分为上北,下南,左西,右东四个方向.向东就是横坐标i不变,纵坐标j加1(i与j其实就是下标).其他方向也可以这样确定.通过上一步 ...