簡體   English   中英

python如何保持一個線程執行直到其他線程完成

[英]python how to keep one thread executing till other threading finished

我希望在操作應用程序(例如,進行猴子測試)時記錄應用程序(例如,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))

您可以使用Thread.join()

import threading, time

def worker():
    time.sleep(5)

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

事件是在線程之間進行通信的好方法( http://docs.python.org/2/library/threading.html#event-objects )。 但是,您將遇到的另一個問題是top命令將永遠運行。 我會做這樣的事情:

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()不需要在線程中運行,但是不確定您擁有哪些其他代碼可能需要它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM