标签:style blog http color os io ar for art
多线程可以共享全局变量,多进程不能。多线程中,所有子线程的进程号相同;多进程中,不同的子进程进程号不同。
1 #!/usr/bin/python 2 # -*- coding:utf-8 -*- 3 import os 4 import threading 5 import multiprocessing 6 count_thread = 0 7 count_process = 0 8 9 # worker function 10 def worker1(sign, lock): 11 global count_thread 12 lock.acquire() 13 count_thread += 1 14 print(sign, os.getpid()) 15 lock.release() 16 17 def worker2(sign, lock): 18 global count_process 19 lock.acquire() 20 count_process += 1 21 print(sign, os.getpid()) 22 lock.release() 23 # Main 24 print(‘Main:‘,os.getpid()) 25 26 # Multi-thread 27 record = [] 28 lock = threading.Lock() 29 for i in range(5): 30 thread = threading.Thread(target=worker1,args=(‘thread‘,lock)) 31 thread.start() 32 record.append(thread) 33 34 for thread in record: 35 thread.join() 36 37 # Multi-process 38 record = [] 39 lock = multiprocessing.Lock() 40 for i in range(5): 41 process = multiprocessing.Process(target=worker2,args=(‘process‘,lock)) 42 process.start() 43 record.append(process) 44 45 for process in record: 46 process.join() 47 48 49 print count_thread 50 print count_process
运行结果
(‘Main:‘, 3142)
(‘thread‘, 3142)
(‘thread‘, 3142)
(‘thread‘, 3142)
(‘thread‘, 3142)
(‘thread‘, 3142)
(‘process‘, 3148)
(‘process‘, 3149)
(‘process‘, 3150)
(‘process‘, 3151)
(‘process‘, 3152)
5
0
python 多线程和多进程的区别 mutiprocessing theading
标签:style blog http color os io ar for art
原文地址:http://www.cnblogs.com/sunny-smile/p/3957782.html