进程变量相互隔离,线程共享全局变量,下面是一个简单的验证?
进程:
from multiprocessing import Process from threading import Thread def get(lis): while Thread: s = lis.pop() print('get %s', s) if __name__ == '__main__': lis = list(range(1, 11)) process1 = Process(target=get, args=(lis,)) process2 = Process(target=get, args=(lis,)) process1.start() process2.start() process1.join() get %s 10 get %s 9 get %s 8 get %s 7 get %s 6 get %s 5 get %s 4 get %s 3 get %s 2 get %s 1 get %s 10 s = lis.pop() get %s 9 IndexError: pop from empty list get %s 8 get %s 7 get %s 6 get %s 5 get %s 4 get %s 3 get %s 2 get %s 1 finished
线程:
from multiprocessing import Process from threading import Thread def get(lis): while Thread: s = lis.pop() print('get %s', s) if __name__ == '__main__': lis = list(range(1, 11)) thread1 = Thread(target=get, args=(lis,)) thread2 = Thread(target=get, args=(lis,)) thread1.start() thread2.start() thread1.join() thread2.join() print('finished') get %s 10 get %s 9 get %s 8 get %s 7 get %s 6 get %s 5 get %s 4 get %s 3 get %s 2 get %s 1 IndexError: pop from empty list finished