简体   繁体   中英

Handling python threads

I am working with python 3.5.2 and I got this situation:

I have task A , boolean var Stop = False and task B , well I want to launch task A and monitor boolean var so when it becomes true I pause task A and when I becomes False again I resume task A; at the same time task B offers stats about task A execution so it must start running since task A does and when task A pauses it must not refresh stats until task A resumes. I need some help to implement this in the simplest way using threads in python 3.5.

Thanks in advance!!

Use a threading.Event instead of a boolean. Its built to be monitored by multiple threads. In this example, task_a and task_a_monitor run a different rates but wait on the same event. The main thread controls them both by set and clear methods. I included a boolean used to tell the threads their work is done and time to exit - but it only has affect when the event is set.

import threading
import time

# use to start/pause/exit task
task_event = threading.Event()
task_event.clear()
exit_task = False

# for display time
start_time = time.time()

def task_a(event):
    while True:
        task_event.wait()
        if exit_task:
                return
        print('{: 3.2f}'.format(time.time() - start_time), 'task_a running...')
        time.sleep(1)

def task_a_monitor(event):
    while True:
        task_event.wait()
        if exit_task:
            return
        print('{: 3.2f}'.format(time.time() - start_time), 'task_a_monitor running...')
        time.sleep(.5)


t1 = threading.Thread(target=task_a, args=(task_event,))
t1.start()
t2 = threading.Thread(target=task_a_monitor, args=(task_event,))
t2.start()

print('{: 3.2f}'.format(time.time() - start_time), 'start task')
task_event.set()
time.sleep(3.5)
print('{: 3.2f}'.format(time.time() - start_time), 'pause task')
task_event.clear()
time.sleep(3.5)
print('{: 3.2f}'.format(time.time() - start_time), 'restart task')
task_event.set()
time.sleep(3.5)
print('{: 3.2f}'.format(time.time() - start_time), 'repause task')
task_event.clear()
time.sleep(3.5)
print('{: 3.2f}'.format(time.time() - start_time), 'terminate task')
exit_task = True
task_event.set()
t1.join()
t2.join()
print('done')

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