<table class="text">
<tr class="li1"><td class="ln"><pre class="de1">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102 全局变量通信 共享全局变量不能适用于多进程编程,可以适用于多线程 def producer(a): a += 100 time.sleep(2) def consumer(a): time.sleep(2) print(a) if __name__ == "__main__": a = 1 my_producer = Process(target=producer,args=(a,)) my_producer.start() my_consumer.start() my_producer.join() my_consumer.join() multiprocessing中的queue不能用于pool进程池 pool中的进程间通信需要使用manager中的queue def producer(queue): queue.put("a") time.sleep(2) def consumer(queue): time.sleep(2) data = queue.get() print(data) if __name__ == "__main__": queue = Manager().Queue(10) pool = Pool(2) pool.apply_async(producer,)) pool.apply_async(consumer,)) pool.close() pool.join() 通过pipe实现进程间通信 pipe的性能高于queue def producer(pipe): pipe.send("bobby") def consumer(pipe): print(pipe.recv()) if __name__ == "__main__": recevie_pipe,send_pipe = Pipe() #pipe只能适用于两个进程 my_producer= Process(target=producer,args=(send_pipe,args=(recevie_pipe,)) my_producer.start() my_consumer.start() my_producer.join() my_consumer.join() def add_data(p_dict,key,value): p_dict[key] = value if __name__ == "__main__": progress_dict = Manager().dict() from queue import PriorityQueue first_progress = Process(target=add_data,args=(progress_dict,"bobby1",22)) second_progress = Process(target=add_data,"bobby2",23)) first_progress.start() second_progress.start() first_progress.join() second_progress.join() print(progress_dict)