'Trying multiprocessing but the program dies before it even starts
I have this code:
from multiprocessing import Process, cpu_count
def readplayerinfo():
y=0
Gameon = True
while Gameon:
y+=1
print('y',y)
if y == 50:
Gameon = False
return None
def main():
islooping = True
x=0
a = Process(target=readplayerinfo,args = ())
a.start()
while islooping:
print('x',x)
x+=1
if x == 100:
islooping = False
a.join()
if __name__ == '__main__':
main()
The goal of the program is to make two process, do a while loop in each process and print the y and x simultaneously(fastest one gets printed first obviously).
But when I run it, the terminal only shows 'x 0' and it freezes
I did my best to research, but it's the first time I try multiprocessing.
So my question is this How do I make this multiprocessing work?
Edit: I have been told that IDLE ide has problem with mutliprocessing so i switched to using the terminal in ubuntu 20.04 and then my output was only the y being printed, then it froze and no x was ever printed. Plus, i did print(cpu_count()) and it returned me 4 so I don't think it's a hardware problem
Solution 1:[1]
I tried a lot of things, but the only way to get x and y to print alternatively is to do 2 different processes. The x and y will print one after the other, but there will be a slight delay between them, because of the overhead of starting a processe.Plus, I don't know why, but IDLE doesn't work well with multiprocessing. So you need to find another IDE or do it in the terminal with 'python3 (nameofthefile).py'.
from multiprocessing import Process, cpu_count
def secondprocess():
y=0
Gameon = True
while Gameon:
y+=1
print('y',y)
if y == 50000:
Gameon = False
return None
def firstprocess():
x = 0
islooping = True
while islooping:
x+=1
print('x',x)
if x == 50000:
islooping = False
def main():
a = Process(target=secondprocess,args = ())
b = Process(target=firstprocess,args = ())
a.start()
b.start()
a.join()
b.join()
if __name__ == '__main__':
main()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | solarchick |
