Skip to content

Commit e8eb8f5

Browse files
committed
einfaches Beispiel für multiprocessing
1 parent 31c1c7a commit e8eb8f5

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

Level_8/prozesse.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#!/usr/bin/env python3
2+
from multiprocessing import Process
3+
from time import sleep
4+
from os import getpid
5+
from sys import argv
6+
7+
"""
8+
multiprocessing ist progammatisch ähnlich zu verwenden wie threading.
9+
Das Modul heißt anders und die Klasse auch (nämlich Process).
10+
"""
11+
12+
class PIDPrinter(Process):
13+
def __init__(self, wait=0.1):
14+
Process.__init__(self)
15+
self.wait = wait
16+
self.daemon = True # siehe Threads
17+
18+
def run(self):
19+
while True:
20+
print(getpid())
21+
sleep(self.wait)
22+
23+
"""
24+
Alternativ kann man auch einfach eine bestimmte Methode
25+
in einem neuen Prozess ausführen ohne eine neue Klasse zu schreiben:
26+
27+
def fun():
28+
pass
29+
30+
Process(target=fun).start()
31+
"""
32+
33+
if len(argv) > 1:
34+
count = int(argv[1])
35+
else:
36+
count = 2
37+
38+
for x in range(count):
39+
PIDPrinter().start()
40+
41+
while True:
42+
sleep(100)
43+
44+
45+

0 commit comments

Comments
 (0)