本文共 1209 字,大约阅读时间需要 4 分钟。
一、进程
import multiprocessingimport osimport signalprocess_id = []num=multiprocessing.Value("d",10.0) #单个值num_array=multiprocessing.Array("i",[1,2,3,4,5]) #主进程与子进程共享这个数组 def func(i,a,array): process_id.append(os.getpid()) while True: print("the {} dog".format(i)) array[0] = a a = i for i in range(10): process = multiprocessing.Process(target=func, args=([i, num, num_array]), daemon=False) # daemon表示守护主进程,这里为了测试杀死进程,将其关闭 process.start()time.sleep(0.2) #等待进程运行pirnt(num)print(num_array[0])#杀死进程for id in process_id: os.kill(int(id), signal.SIGKILL)
二、线程(默认数组、字典等变量全局共享,可以直接在方法内调用全局变量值,而无需传递)
from threading import ThreadthreadId = []stop_threads = False #判定符,为true时,退出线程方法,即杀死线程array = [1,2,3,4,5]def func(i): while True: print("the {} dog".format(i)) array[i] = i + 2 if stop_threads: breakfor i in range(len(array)): thread = Thread(target=func, args=([i,]), daemon=False) # 关闭守护 thread.start() threadId.append(thread) # 记录线程对象time.sleep(0.5)print(array)stop_threads = True # 判定符开启for t1 in threadId: t1.join() # 阻塞,等子线程运行完,在运行主线程 print('thread killed')threadId = [] # 置空线程池stop_threads = False # 判定符关闭
转载地址:http://euagj.baihongyu.com/