Multi-process and multi-thread
Multi-process and multi-thread
#! /Usr/bin/python #-*-coding: UTF-8-*-import osimport threadingimport multiprocessingimport time # Process entrydef process_worker (sign, lock, function): global count_process # lock. acquire () count_process + = 1 print (sign, OS. getpid () print apply (function) # lock. release () # Thread entrydef thread_worker (sign, lock, function): global count_thread lock. acquire () count_thread + = 1 print (sign, OS. getpid () print apply (function) lock. release () # real work functions def Lee (): return 'I am Lee' def Marlon (): return 'I am Marlon' def Allen (): return 'I am Allen' count_thread = 0count_process = 0if _ name __= = '_ main _': # Multi-process begin multiprocessing. freeze_support () # required in window python. Otherwise, many processes may be opened at will. print ('main: ', OS. getpid () record = [] lock = multiprocessing. lock () func_list = [Lee, Marlon, Allen] for function in func_list: process = multiprocessing. process (target = process_worker, args = ('process', lock, function) Process. start () record. append (process) for process in record: process. join () print "count_process value is", count_process # This value has not changed, and Multi-process does not share memory # Multi-thread begin record = [] lock = threading. lock () for function in func_list: thread = threading. thread (target = thread_worker, args = ('thread', lock, function) thread. start () record. append (thread) for thread in record: thread. join () print "count_thread value is", count_thread # This value is changed, so multi-thread shared memory