1. 实例一
主进程跟子进程的通过两个队列实现全双工通信; 如有需要主进程会提示窗口输入信息传输给子进程; 如果子进程收到主进程的消息,会弹窗提示收到的消息; 子进程弹窗提示进程即将结束; 详细代码如下
import multiprocessing
import random
import threading
import timeimport FreeSimpleGUI as sg def worker ( num, main_queue, sub_queue, lock) : """子进程工作函数""" x = None time. sleep( 1 ) msg = random. choice( [ True , False ] ) if msg is True : with lock: message = f'进程 { num} 需要修改!' sub_queue. put( message) x = main_queue. get( ) if x: sg. popup( f"子进程 { num} 收到主进程发送过来的信息: { x} " , keep_on_top= True ) sg. popup( f"子进程 { num} 进程已结束!" , keep_on_top= True ) print ( F"进程 { num} 执行完成!" ) def thread_worker ( main_queue, sub_queue, lock, num_processes) : """子线程工作函数,启动进程池并管理管道""" with multiprocessing. Pool( processes= num_processes) as pool: pool. starmap( worker, [ ( i, main_queue, sub_queue, lock) for i in range ( num_processes) ] ) pool. close( ) pool. join( ) sub_queue. put( "任务都已执行完成!" ) def main ( ) : layout = [ [ sg. Button( '启动任务' ) ] , [ sg. Text( '' , size= ( 30 , 1 ) , key= '-OUTPUT-' ) ] ] window = sg. Window( '主窗口' , layout) manager = multiprocessing. Manager( ) lock = manager. Lock( ) main_queue = manager. Queue( ) sub_queue = manager. Queue( ) while True : event, values = window. read( timeout= 100 ) if event == sg. WIN_CLOSED: break if event == '启动任务' : threading. Thread( target= thread_worker, args= ( main_queue, sub_queue, lock, 5 ) , daemon= True ) . start( ) while not sub_queue. empty( ) : message = sub_queue. get( ) if not message == "任务都已执行完成!" : window[ '-OUTPUT-' ] . update( message) main_queue. put( sg. popup_get_text( message + "主进程输入修改值" ) ) else : window[ '-OUTPUT-' ] . update( message) window. close( ) if __name__ == "__main__" : main( )