89 lines
2.4 KiB
Python
89 lines
2.4 KiB
Python
|
import multiprocessing as mp
|
||
|
import time
|
||
|
import os
|
||
|
import threading
|
||
|
|
||
|
|
||
|
# ----------------------------------------範例4------------------------------
|
||
|
# A報數
|
||
|
def A_Count_off():
|
||
|
for i in range(0,5):
|
||
|
print(f'A : {i}')
|
||
|
time.sleep(0.5)
|
||
|
|
||
|
|
||
|
# B報數
|
||
|
def B_Count_off():
|
||
|
for i in range(5,10):
|
||
|
print(f'B : {i}')
|
||
|
time.sleep(0.5)
|
||
|
|
||
|
#
|
||
|
# if __name__=='__main__':
|
||
|
# process_list=[A_Count_off,B_Count_off]
|
||
|
# process_name =[]
|
||
|
# for i in range(0,len(process_list)):
|
||
|
# process_name.append(mp.Process(target=process_list[i]))
|
||
|
#
|
||
|
# for i in range(0,len(process_name)):
|
||
|
# process_name[i].start()
|
||
|
# # process_name[i].join()
|
||
|
#
|
||
|
# for i in range(0,len(process_name)):
|
||
|
# process_name[i].join()
|
||
|
|
||
|
|
||
|
# ----------------------------------------範例5------------------------------
|
||
|
|
||
|
def Count_off(code_name):
|
||
|
print('process {} '.format(os.getpid()))
|
||
|
print('thread {} '.format(threading.current_thread().name))
|
||
|
for i in range(0,5):
|
||
|
print(f'{code_name} : {i}')
|
||
|
time.sleep(0.5)
|
||
|
|
||
|
# if __name__=='__main__':
|
||
|
# process_name_list=["A","B","C","D"]
|
||
|
# process_list=[]
|
||
|
# for i in range(0,len(process_name_list)):
|
||
|
# process_list.append(mp.Process(target=Count_off,args=process_name_list[i]))
|
||
|
# for i in range(0,len(process_list)):
|
||
|
# process_list[i].start()
|
||
|
# for i in range(0,len(process_list)):
|
||
|
# process_list[i].join()
|
||
|
|
||
|
|
||
|
|
||
|
# ----------------------------範例6-----------------------------
|
||
|
class Process_class(mp.Process):
|
||
|
def __init__(self, code_name):
|
||
|
mp.Process.__init__(self)
|
||
|
self.code_name = code_name
|
||
|
|
||
|
def run(self):
|
||
|
print('process {} '.format(os.getpid())) # 查看進程
|
||
|
print('thread {} '.format(threading.current_thread().name)) # 查看線程
|
||
|
for i in range(0,5):
|
||
|
print(f'{self.code_name} : {i}')
|
||
|
time.sleep(0.5)
|
||
|
def test_return(self):
|
||
|
return(f'{self.code_name}=END')
|
||
|
|
||
|
if __name__=='__main__':
|
||
|
start_time = time.time()
|
||
|
process_name_list = ["A", "B", "C", "D"]
|
||
|
process_list = []
|
||
|
for i in range(0, len(process_name_list)):
|
||
|
process_list.append(Process_class(process_name_list[i]))
|
||
|
for i in range(0, len(process_list)):
|
||
|
process_list[i].start()
|
||
|
for i in range(0, len(process_list)):
|
||
|
process_list[i].join()
|
||
|
|
||
|
for i in range(0, len(process_list)):
|
||
|
print(process_list[i].test_return())
|
||
|
|
||
|
|
||
|
|
||
|
|