Reputation: 4237
everytime when running this program, I hear my cpu fan is boosting. I suspected the busy waiting while loops in the code is the cause. I wonder how a real programmer will do to optimize this?
from multiprocessing import Process, Queue
import threading
class PThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
#view leave will set this event
self.event = threading.Event()
def run(self):
while 1:
if not self.event.is_set():
print 'run'
else:
break
def server_control(queue):
while True:
try:
event = queue.get(False)
except:
event = None
if event == 'DETECTED':
print 'DETECTED'
t = PThread()
t.start()
elif event == 'LEAVE':
print 'Viewer_left'
t.event.set()
t.join()
elif event == 'QUIT':
break
q=Queue()
p = Process(target=server_control, args=(q,))
p.start()
p.join()
Upvotes: 2
Views: 173
Reputation: 3672
The multiprocessing module has a clone of threading's event object
from multiprocessing import Process, Event
Instead of use a Queue. You should declare event of interest in your main and pass them to other process In your case:
detected = Event()
leave = Event()
exit = Event()
Process(target=server_control, args=(detected, leave, exit))
and finally check if the event is fired or wait in your loop
Upvotes: 1
Reputation: 50682
You might make the loop a bit less tight by adding a time.sleep(0)
in the loop to pass the remainder of the quantum to another thread.
See also: How does a threading.Thread yield the rest of its quantum in Python?
Upvotes: 0
Reputation: 34573
If a thread needs to wait for an event, it should sleep until the event occurs, rather than busy-waiting. Your event object has a wait()
method that can be used to accomplish that. Call it, and it won't return until some other thread has called set()
on the event (or the timeout elapses, if you specify one). In the meantime, the thread uses no CPU.
Upvotes: 5