标签:style blog color os io ar for 文件 art
import os import threading import multiprocessing # worker function def worker(sign, lock): lock.acquire() print(sign, os.getpid()) lock.release() if __name__ == ‘__main__‘: print(‘Main:‘,os.getpid()) # Multi-thread record = [] lock = threading.Lock() for i in range(5): thread = threading.Thread(target=worker,args=(‘thread‘,lock)) thread.start() record.append(thread) for thread in record: thread.join() # Multi-process record = [] lock = multiprocessing.Lock() for i in range(5): process = multiprocessing.Process(target=worker,args=(‘process‘,lock)) process.start() record.append(process) for process in record: process.join()
__name__是指示当前py文件调用方式的方法。如果它等于"__main__"就表示是直接执行,如果不是,则用来被别的文件调用,这个时候if就为False,那么它就不会执行最外层的代码了。
这样的话,子进程一载入这个文件,就会调用 processFunc 函数,会执行生成子进程的代码,因为他是最外层代码,或者叫做全局代码,从而产生多个进程。
标签:style blog color os io ar for 文件 art
原文地址:http://www.cnblogs.com/qiqing/p/3964473.html