Python如何保持一个线程一直执行直到其他线程完成
我希望在使用某个应用程序(比如 com.clov4r.android.nil)时,记录它的 CPU 占用情况(比如在进行猴子测试的时候),然后在我退出这个应用程序(比如结束猴子测试)时停止记录。请问怎么用 Python 实现这个功能呢?
以下是一些代码:
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))
2 个回答
0
你可以使用 Thread.join() 方法:
import threading, time
def worker():
time.sleep(5)
t = threading.Thread(target=worker)
t.start()
t.join()
print('finished')
0
事件是一种很好的方式,可以让不同的线程之间进行沟通(http://docs.python.org/2/library/threading.html#event-objects)。不过,你还会遇到另一个问题,就是最上面的命令基本上会一直运行下去。我会这样做:
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()
可能还有其他方法可以结束线程,但那样做看起来不太好,这种方法控制得更好。
我还想说,run_monkey() 这个函数其实不需要在一个线程里运行,但我不太确定你还有什么其他代码可能需要它。