微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python线程与Linux中的多处理

基于这个问题,我认为创build新进程应该在Linux中创build新线程 一样快 。 但是,一点testing显示非常不同的结果。 这是我的代码

from multiprocessing import Process,Pool from threading import Thread times = 1000 def inc(a): b = 1 return a + b def processes(): for i in xrange(times): p = Process(target=inc,args=(i,)) p.start() p.join() def threads(): for i in xrange(times): t = Thread(target=inc,)) t.start() t.join()

testing:

>>> timeit processes() 1 loops,best of 3: 3.8 s per loop >>> timeit threads() 10 loops,best of 3: 98.6 ms per loop

所以,创build过程几乎要慢40倍 ! 为什么会发生? 它是特定于Python还是这些库? 还是我刚刚误解了上面的答案?

UPD 1.更清楚。 我知道这段代码实际上并没有引入任何并发。 这里的目标是testing创build进程和线程所需的时间。 要使用真正的并发与Python可以使用这样的事情:

我怎样才能平行这个字计数function?

进程子类可以在Linux上运行,但不能在Windows上运行

locking内存分配争用 – multithreading与多进程

为什么在一个多处理器中,所有的@R_502_6273@都不能被均匀利用?

如何设置优先级来获取C / C ++中的互斥量

def pools(): pool = Pool(10) pool.map(inc,xrange(times))

它的运行速度比线程版本要快得多。

UPD 2.我已经添加os.fork()版本:

for i in xrange(times): child_pid = os.fork() if child_pid: os.waitpid(child_pid,0) else: exit(-1)

结果是:

$ time python test_fork.py real 0m3.919s user 0m0.040s sys 0m0.208s $ time python test_multiprocessing.py real 0m1.088s user 0m0.128s sys 0m0.292s $ time python test_threadings.py real 0m0.134s user 0m0.112s sys 0m0.048s

是否有可能在一个shell脚本内创build一个非subprocess?

有没有办法来检查一个模块是否被Windows中的多处理标准模块加载?

当从脚本文件扩展名关联运行时,python多处理在Windows 7上失败

父进程如何通过调用_exit的subprocess获得终止状态

多处理启动太多的Python VM实例

链接到的问题是比较只调用fork(2)和pthread_create(3)的代价,而你的代码做的更多,例如使用join()等待进程/线程终止。

如果如你所说…

这里的目标是测试创建进程和线程所需的时间。

那么你不应该等待他们完成。 你应该使用更像这样的测试程序…

fork.py

import os import time def main(): for i in range(100): pid = os.fork() if pid: #print 'created new process %d' % pid continue else: time.sleep(1) return if __name__ == '__main__': main()

thread.py

import thread import time def dummy(): time.sleep(1) def main(): for i in range(100): tid = thread.start_new_thread(dummy,()) #print 'created new thread %d' % tid if __name__ == '__main__': main()

给出以下结果…

$ time python fork.py real 0m0.035s user 0m0.008s sys 0m0.024s $ time python thread.py real 0m0.032s user 0m0.012s sys 0m0.024s

…所以线程和进程的创建时间没有太大的区别。

是的,它是真实的。 开始一个新的过程(称为重量级过程)是昂贵的。

作为一个概述…

操作系统必须(在linux的情况下)分叉第一个进程,为新进程设置记帐,设置新堆栈,执行上下文切换,复制任何被更改的内存,并在新过程返回。

线程只是分配一个新的堆栈和线程结构,执行上下文切换,并在工作完成时返回。

…这就是为什么我们使用线程。

根据我的经验,在创建线程(使用pthread_create )和分支进程之间存在显着差异。

例如,我创建了一个类似于你的Python测试的C测试,线程代码如下:

pthread_t thread; pthread_create(&thread,NULL,&test,NULL); void *res; pthread_join(thread,&res);

并像这样处理分叉代码

pid_t pid = fork(); if (!pid) { test(NULL); exit(0); } int res; waitpid(pid,&res,0);

在我的系统上,分叉代码需要执行8次左右。

不过,值得注意的是python的实现速度更慢 – 对我来说慢了大约16倍。 我怀疑这是因为除了创建新进程的常规开销之外,还有更多与新进程相关的python开销。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐