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方法会被同时调用

输出结果

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的结果没有规律.

你可能感兴趣的:(python threding和multiprocessing比较)