Skip to content

Commit 4b328aa

Browse files
committed
added
1 parent 3176b13 commit 4b328aa

2 files changed

Lines changed: 61 additions & 0 deletions

File tree

python/process/multiprocess.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import multiprocessing
2+
import time
3+
4+
def process(num):
5+
time.sleep(num)
6+
print 'Process:', num
7+
8+
if __name__ == '__main__':
9+
for i in range(5):
10+
p = multiprocessing.Process(target=process, name=str(i)+"_xxx", args=(i,))
11+
p.start()
12+
13+
print('CPU number:' + str(multiprocessing.cpu_count()))
14+
for p in multiprocessing.active_children():
15+
print('Child process name: ' + p.name + ' id: ' + str(p.pid))
16+
17+
print('Process Ended')

python/process/myprocess.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
from multiprocessing import Process, Lock, Semaphore, Queue
5+
import time
6+
7+
buffer = Queue(10)
8+
empty = Semaphore(2)
9+
full = Semaphore(0)
10+
lock = Lock()
11+
12+
class Consumer(Process):
13+
def run(self):
14+
global buffer, empty, full, lock
15+
while True:
16+
full.acquire()
17+
lock.acquire()
18+
buffer.get()
19+
print('Consumer pop an element')
20+
time.sleep(1)
21+
lock.release()
22+
empty.release()
23+
24+
class Producer(Process):
25+
def run(self):
26+
global buffer, empty, full, lock
27+
while True:
28+
empty.acquire()
29+
lock.acquire()
30+
buffer.put(1)
31+
print('Producer append an element')
32+
time.sleep(1)
33+
lock.release()
34+
full.release()
35+
36+
if __name__ == '__main__':
37+
p = Producer()
38+
c = Consumer()
39+
p.daemon = c.daemon = True
40+
p.start()
41+
c.start()
42+
p.join()
43+
c.join()
44+
print "Ended!"

0 commit comments

Comments
 (0)