Python中的multiprocessing和threading
Python中的multiprocessing和threading分别使用来实现多进程编程和多线程编程的。其中threading比较简单,而前者比较繁琐。
下面,我们进行一下分析:
多线程——threading
最简单的多线程编程的例子
上代码:
import threading
def threading_func(name):
print "This is Function %s" % (name)
if __name__ == '__main__':
threadings = []
for i in xrange(1, 5):
temp_thread = threading.Thread(target=threading_func, args=(str(i),))
threadings.append(temp_thread)
temp_thread.start()
for one_thread in threadings:
one_thread.join()
这个程序执行的结果为:
This is Function 1
This is Function 2
This is Function 3
This is Function 4
[Finished in 0.1s]
其中可以看到几个Thread类的使用方法,
- 使用list来记录所有的线程
- 声明一个线程时使用的方法为threading.Thread(target=xxx ,args=(xxx))其中这个
target填写的是该线程中简要运行的方法名,args中要以元组的形式给出这个方法的参数。- 使用
start()方法来开始这个线程- 使用
join()方法来“合并线程”,合并的意思是:若在线程A中执行了C.join(),表示在C执行完毕后再去A中的join后开始执行。我们在主线程中一次调用所有线程的join(),表示所有线程均结束后,后面的语句才可以执行。与这个函数容易混淆的是setDaemon(True),Daemon是“后台”的意思,这个函数(True时)可以将一个线程设置为“后台线程”,主线程不考虑子线程的执行,一旦主线程执行完毕,则被终止,同时终止所有子线程的执行。当然,setDaemon(True)和join()不同的是,前者需要在start()方法被调用前执行。另外,在join()方法中还可以设置Timeout,当join()方法没有设置Timeout时,主调线程会一直被阻塞到被调线程结束,若设置Timeout的话,则主调线程会被阻塞Timeout所设定的时间。
创建进程除了上面说的那种方法以外,还有另外一种方法,集成Thread类,具体写法如下:
import threading
class MyThread(threading.Thread):
def __init__(self, ...):
threading.Thread.__init__(self)
self.xxx = ... # 设置其他属性
def run(self):
# code
将线程需要执行的代码全部放在run函数的code处即可。
进程通信
目前我只是搞了搞简单的进程通信,使用event类。
import threading
import time
class MyThread(threading.Thread):
def __init__(self, signal):
threading.Thread.__init__(self)
self.signal = signal
def run(self):
print "I am %s, I will sleep" % (self.name)
self.signal.wait()
print "I an %s, I awake" % (self.name)
if __name__ == '__main__':
signal = threading.Event()
for t in xrange(0, 3):
thread = MyThread(signal)
thread.start()
print "main thread sleep 3 seconds"
time.sleep(3)
signal.set()
这种写法就是上面所说的那种集成thread类的写法,signal是一个threading.Event()类型的变量,所有进程都执行到self.signal.wait()这里后等待signal被设置,当主进程执行到signal.set()时,会设置signal,表示发送了一个信号,唤醒全部阻塞在signal.wait()的进程,这叫做进程通信。更多内容等待以后学习。
进程互斥
有时候,我们希望两个进程不要同时更改一个资源,这时候我们就需要加上互斥锁mutex。代码如下:
import threading
import time
counter = 0
mutex = threading.Lock()
class MyThread(threading.Thread):
def __init__(self):
# super(MyThread, self).__init__(self)
threading.Thread.__init__(self)
self.setName("Big Thread" + self.name)
def run(self):
global counter, mutex
time.sleep(1)
if mutex.acquire():
counter += 1
print "I am %s, set counter %d" % (self.name, counter)
mutex.release()
if __name__ == '__main__':
for i in xrange(200):
my_thread = MyThread()
my_thread.start()
在每一个run函数中,都有以下方法:
mutex.acquire()获得锁,即加上锁。mutex.release释放锁,即解锁。当无法获得锁时,进程将会被阻塞,直到获得锁。上述代码执行结果为:
I am Big ThreadThread-1, set counter 1
I am Big ThreadThread-5, set counter 2
I am Big ThreadThread-2, set counter 3
I am Big ThreadThread-4, set counter 4
I am Big ThreadThread-3, set counter 5
[Finished in 1.0s]
可见counter这个变量是按照顺序加的,尽管进程号不是递增的。若我们将所有关于所的代码注释掉,得到以下代码:
I am Big Thread Thread-1, set counter 1
I am Big Thread Thread-2, set counter 2
I am Big Thread Thread-3, set counter 3
I am Big Thread Thread-6, set counter 4
I am Big Thread Thread-8, set counter 5I am Big Thread Thread-5, set counter 6
I am Big Thread Thread-10, set counter 7
I am Big Thread Thread-9, set counter 9
I am Big Thread Thread-7, set counter 8
I am Big Thread Thread-4, set counter 10
[Finished in 1.0s]
结构非常混乱。
Python中的multiprocessing和threading的更多相关文章
- python中多进程multiprocessing、多线程threading、线程池threadpool
浅显点理解:进程就是一个程序,里面的线程就是用来干活的,,,进程大,线程小 一.多线程threading 简单的单线程和多线程运行:一个参数时,后面要加逗号 步骤:for循环,相当于多个线程——t=t ...
- python 中的multiprocessing 模块
multiprocessing.Pipe([duplex]) 返回2个连接对象(conn1, conn2),代表管道的两端,默认是双向通信.如果duplex=False,conn1只能用来接收消息,c ...
- python中的锁lock=threading.Lock()
避免多个线程保卫同一块数据的时候,产生错误,所以加锁来防止这种问题 个人理解:当打印结果是交替打印时,但是如果需求是需要打印完一个线程的内容后,再去打印另一个线程的内容,就需要用到锁 不加锁打印结果: ...
- 关于python中的多进程模块multiprocessing
python中的multiprocessing是一个多进程管理包,主要作用也就是提供多进程,而不是多线程,在其中用的比较多估计也就是Process和Pipe两个类,如下代码所示: #!/usr/bin ...
- python中进程、线程、协程简述
进程 python中使用multiprocessing模块对进程进行操作管理 进程同步(锁.信号量.事件) 锁 —— multiprocessing.Lock 只要用到了锁 锁之间的代码就会变成同步的 ...
- Python多进程库multiprocessing创建进程以及进程池Pool类的使用
问题起因最近要将一个文本分割成好几个topic,每个topic设计一个regressor,各regressor是相互独立的,最后汇总所有topic的regressor得到总得预测结果.没错!类似bag ...
- python中的进程、线程(threading、multiprocessing、Queue、subprocess)
Python中的进程与线程 学习知识,我们不但要知其然,还是知其所以然.你做到了你就比别人NB. 我们先了解一下什么是进程和线程. 进程与线程的历史 我们都知道计算机是由硬件和软件组成的.硬件中的CP ...
- python中multiprocessing模块
multiprocess模块那来干嘛的? 答:利用multiprocessing可以在主进程中创建子进程.Threading是多线程,multiprocessing是多进程. #该模块和Threadi ...
- python中threading的用法
摘自:http://blog.chinaunix.net/uid-27571599-id-3484048.html 以及:http://blog.chinaunix.net/uid-11131943- ...
随机推荐
- 菜鸟学习 - Unity中的热更新 - LuaInterface用户指南
[由于学习,所以翻译!] 1.介绍 LuaInterface 是 Lua 语言和 Microsoft.NET 平台公共语言运行时 (CLR) 之间的集成库. 非常多语言已经有面向 CLR 编译器和 C ...
- 一些Android程序的反逆向方法
1.检测调试器 在代码中检测调试器的动态调试 首先在AndroidMainfest.xml文件中设置android:debuggable="false",让程序不可调试.这样别人想 ...
- [转] What is Ec/Io (and Eb/No)?
PS:http://www.telecomhall.com/what-is-ecio-and-ebno.aspx If someone asks you "Which Signal Leve ...
- Java基础知识强化77:正则表达式之获取功能(Pattern 和 Matcher类的使用)
1. 获取功能: Pattern 和 Matcher类结合使用 2. 使用案例: package cn.itcast_05; import java.util.regex.Matcher; impor ...
- java transient关键字和transaction的区别
transient:表示临时的,不会被持久化,保存进数据库 transaction:表示事务 <div style="background: #fff; color: #0ff;&qu ...
- sharepoint查询超出阈值
昨天客户出了webpart显示数据不稳定的bug,经过这两天的艰苦排查终于发现了是列表视图阈值造成的问题,经过在网上搜索终于找到了类似的解决方法. SPQuery query = new SPQuer ...
- IIS应用程序池数目
今天突然遇到一个问题,访问线上站点,数据处理过之后,访问页面有时是404,有时不是404,而404页面刷新几次之后就正常了. 经过大神们指点之后,发现竟然是应用程序池惹的祸. 分析下原因,在代码里面数 ...
- Hadoop错误
1.50030页面起不来 $bin/hadoop jobtracker 出现:…… SHUTDOWN_MSG: Shutting down JobTracker at node0/ 解决办法:按提示信 ...
- 武汉科技大学ACM:1007: 不高兴的津津
Problem Description 津津上初中了.妈妈认为津津应该更加用功学习,所以津津除了上学之外,还要参加妈妈为她 报名的各科复习班.另外每周妈妈还会送她去学习朗诵.舞蹈和钢琴.但是津津如果一 ...
- 武汉科技大学ACM :1004: 零起点学算法74——Palindromes _easy version
Problem Description “回文串”是一个正读和反读都一样的字符串,比如“level”或者“noon”等等就是回文串.请写一个程序判断读入的字符串是否是“回文”. Input 输入包含多 ...