How to make spawned process wait forever till an item appears in queue in python

91 views Asked by At

I have two classes that I use to automate gdb from the command line, the main class creates a process for it to execute gdb commands from the command-line, then sends commands to the gdb_engine class(which I override the run() method in, it also has the gdb related functions in it) depending on the user request. The two separate processes communicate from the queue which holds the jobs that should be done. To do this task, I thought of this simple plan:

1-Check queue
2-wait if queue is empty, if not, execute the first function in the queue
3-Rewrite the queue
4-return to 1

But I couldn't find any function in multiprocessing documentary to make the spawned process stop/sleep if the queue is empty. I'm sure that there's a way to do this but since I'm still a beginner at python, I can't find my way easily. Things are still a bit confusing at this point.

Thanks in advance, have a good day! (I use python3.4 btw, if that matters)

EDIT: I don't have much going on right now but still posting my code on grzgrzgrz3's request. The codebase is somewhat large so I'm only copy/pasting the multiprocessing related ones.

GDB_Engine class, where I control gdb with pexpect:

class GDB_Engine(Process):
jobqueue=Queue()
def __init__(self):
    super(GDB_Engine, self).__init__()
    self.jobqueue=GDB_Engine.jobqueue

def run(self):
    #empty since I still don't know how to implement that algorithm

Main of the program

if __name__ == "__main__":
gdbprocess=GDB_Engine()
gdbprocess.start()

I simply put items in queue whenever I need to do a job like this(middle of the code that attaches gdb to the target):

gdbprocess.jobqueue.put("attachgdb")

My main idea about it is spawned process will compare the string in queue and run the specified function in GDB_Engine class, to show an example, here's the attach code:

def attachgdb(self,str):
    global p
    p=pexpect.spawnu('sudo gdb')
    p.expect_exact("(gdb) ")
    p.sendline("attach " + str)
    p.expect_exact("(gdb) ")
    p.sendline("c")
    p.expect_exact("Continuing")
1

There are 1 answers

0
Korcan Karaokçu On BEST ANSWER

I just found out that get() method blocks the process automatically if the queue is empty, so the answer to my question was very simple. I should have tried the methods more before asking, looks like it was just another silly and unnecessary question of mine.