python threding和multiprocessing比较

import threading
import time
class x(threading.Thread):
    def __init__(self,i):
        self.a=i 
	super(x,self).__init__()
        self.start()
    def run(self):
	if self.a==2:
		time.sleep(1)
	print self.a
for i in range(4):                     
    x(i)                         #每个x(i)已是一个线程了,他们的run方法会被同时调用

输出结果python

root@VM-131-71-ubuntu:~/python# python a.py 
0
1
3
4
5
6
7
8
9
2                                #若是x(i)的run方法仍是顺序执行,没有并发,那么2不该该在这里打印出来


from multiprocessing import Process
import time
def b(i):
   if i==2:
       time.sleep(3)
   print i
for i in range(10):
   Process(target=b,args=(i,)).start()
3
4
5
1
6
7
8
9
0
2                             #能够看出也是并发的,而且和上面的不同,每一次的结果都是不必定的.

threding每一次的结果都必定,multiprocessing的结果没有规律.ubuntu

相关文章
相关标签/搜索