简体   繁体   中英

How to run multiple functions using thread measuring time?

I want to run two functions concurrently until they both return True up to 60 sec timeout.

This is what I have:

import time 

start_time = time.time()
timeout = time.time() + 60

a_result = b_result = False
a_end_time = b_end_time = None
a_duration = b_duration = None

while time.time() < timeout :
    if not a_result:
        a_result = func_a()
        if a_result:
            a_end_time = time.time()

    if not b_result:
        b_result = func_b()
        if b_result:
            b_end_time = time.time()
    if a_result and b_result:
        break

if a_end_time:
    a_duration = a_end_time - start_time
if b_end_time:
    b_duration = b_end_time - start_time

print a_duration,b_duration

if not (a_result and b_result):
    raise Exception("exceeded timeout")

How can I improve this using threading?

I think it would be easiest to implement if each function timed itself:

import random
import time
import threading

MAX_TIME = 20
a_lock, b_lock = threading.Lock(), threading.Lock()
a_result = b_result = False
a_duration = b_duration = None

def func_a():
    global a_result, a_duration

    start_time = time.time()
    time.sleep(random.randint(1, MAX_TIME))  # do something...
    a_duration = time.time() - start_time
    with a_lock:
        a_result = True

def func_b():
    global b_result, b_duration

    start_time = time.time()
    time.sleep(random.randint(1, MAX_TIME))  # do something...
    b_duration = time.time() - start_time
    with b_lock:
        b_result = True

th1 = threading.Thread(target=func_a)
th1.deamon = True

th2 = threading.Thread(target=func_b)
th2.deamon = True

th1.start()
th2.start()
timeout = time.time() + MAX_TIME
while time.time() < timeout:
    if a_result and b_result:
        break

if not (a_result and b_result):
    raise Exception("exceeded timeout")

print('func_a: {} secs, func_b: {} secs'.format(a_duration, b_duration))

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