简体   繁体   中英

How to wait for a thread to finish before continuing

I need to run a function in another thread, and get the return value of that function to save it to a variable in the main thread. Basically, my code calls the function, which communicates with a balance through a serial port, waits for and gets the response, parses the response, and returns the response as a float. I need to capture this float so I can save it. This is my code:

from multiprocessing.pool import ThreadPool

pool = ThreadPool(processes=2)
result = pool.apply_async(manual_short_command, (self.status_signal2, self.conn, command, status_string, 2))
self.readout = result.get()

def manual_short_command(signal, conn, command, status_string, string_arg='', timeout=60):
""" Send specified command (expects a balance response)to balance through "conn" and emit status signal """
print "Command: " + command.strip('\r\n')
emit_status(signal, status_string[0], string_arg)
if not conn.isOpen():
    conn.open()
# Wait until nothing can be read at the balance port
while not timeout and conn.readlines():
    time.sleep(1)
    timeout -= 1
# Write the command to the balance port and wait for response
while timeout:
    time.sleep(1)
    conn.write(command)
    resp = conn.readlines()

    try:
        resp = float(resp[0])
    except ValueError:
        pattern = r'(.?\d+\.\d+)'
        match = re.findall(pattern, resp[0])
        resp = float(match[0])
    except IndexError:
        continue

    print resp
    print 'timeout: %s' % timeout
    if resp:
        emit_status(signal, status_string[1], str(resp))
        print resp, 'here'
        return resp

    timeout -= 1
conn.close()
print resp
return resp

I start the function manual_short_command in another thread, and this function sends a command through a serial port and waits for a response. It then returns this response and writes it on the status browser (I'm using PyQt4 for the GUI but I think that is irrelevant).

I get an error when I try to assign self.readout = result.get() , saying IndexError: list index out of range , which means that the function hasn't completed in the other thread yet. How do I wait for the thread to finish before I assign the result? My program hangs otherwise. I looked at Threading pool similar to the multiprocessing Pool? for some guidance, but I couldn't find how to synchronize the two threads. Any suggestions? Sorry for the huge block of code.

You can use join() . This will make the program to wait until the thread finish, and then will move next to show the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM