简体   繁体   中英

python how to keep one thread executing till other threading finished

I hope to record app(eg.com.clov4r.android.nil) the CPU occupancy when I operate the app(eg.doing monkey test) and finish recording when I eixt the app(eg.finishing monkey test). How to realise it with python?

Some codes:

packagename = 'com.clov4r.android.nil'
cmd1 = 'adb shell top -d 5 | grep com.clov4r.android.nil'
cmd2 = 'adb shell monkey -v -p com.clov4r.android.nil --throttle 500 --ignore-crashes --ignore-timeouts --ignore-security-exceptions --monitor-native-crashes -s 2345 100'
t1 = threading.Thread(target=subprocess.call(cmd1, stdout=open(r'123.txt', 'w'))) 
t2 = threading.Thread(target=subprocess.call(cmd2))

You can use Thread.join() :

import threading, time

def worker():
    time.sleep(5)

t = threading.Thread(target=worker)
t.start()
t.join()
print('finished')

Events are a good way to communicate between threads ( http://docs.python.org/2/library/threading.html#event-objects ). However, the other problem you will have is that the top command will essentially run forever. I would do something like this:

def run_top(event, top_cmd):
    s = subprocess.Popen(top_cmd, stdout=open('123.txt', 'w'))
    event.wait()  # Wait until event is set, then kill subprocess
    s.kill()

def run_monkey(event, monkey_cmd):
    subprocess.call(monkey_cmd)
    event.set()  # Once we're finished set the event to tell the other thread to exit

event = threading.Event()
threading.Thread(target=run_top, args=(event, your_top_command)).start()
threading.Thread(target=run_monkey, args=(event, your_monkey_command)).start()

There might be a way to kill the thread as well but that's pretty ugly, this way is much more controlled.

I would also say run_monkey() doesn't need to be run in a thread, but not sure what other code you have that may require it.

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