小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

Python線程:同時運行2個不同的函數(shù)

 印度阿三17 2019-05-29

我有一個函數(shù)foo,只有在滿足條件后才會停止.當foo正在運行時,我需要一直詢問用戶輸入(不斷詢問用戶輸入).我希望它們分開運行而不會相互干擾.

在下面的示例中,foo繼續(xù)打印’Hello’并且getUserInput繼續(xù)查找用戶輸入.即使我沒有為用戶輸入輸入任何內(nèi)容,我也希望foo繼續(xù)打印你好.只要用戶沒有輸入字母’e’,它就會一直詢問輸入.我有以下嘗試:

import threading
from time import sleep

class test:
    def __init__(self):
        self.running = True

    def foo(self):
        while(self.running):
            print 'Hello\n'
            sleep(2)

    def getUserInput(self):
        x = ''
        while(x != 'e'):
            x = raw_input('Enter value: ')
        self.running = False

    def go(self):
        th1 = threading.Thread(target=self.foo)
        th2 = threading.Thread(target=self.getUserInput)
        th1.start()
        th2.start()


t = test()
t.go()

我的代碼打印出第一個問候語并要求輸入,但之后沒有任何內(nèi)容.我究竟做錯了什么?感謝您的幫助.

解決方法:

更新:開啟者在IDLE上的Windows上運行他的代碼.關(guān)于I / O,它的行為與shell或Windows命令行不同.他的代碼適用于Windows命令行.

原則上,您的代碼適合我.我正在運行Python 2.6.5.

這里有幾條評論:

1)在你的情況下,只有兩個線程是好的:主線程和另一個線程.但是,它也可以使用三個.只是你的主線程只是等待其他線程完成.

2)你應(yīng)該明確地加入()你產(chǎn)生的所有線程.您在終止它之前在主線程中執(zhí)行此操作.記錄你產(chǎn)生的線程(例如在列表線程中),然后在程序結(jié)束時加入它們(例如,對于線程中的t:t.join()).

3)您在線程之間共享變量self.running.在這種情況下它很好,因為一個線程只讀取它而另一個只寫它.通常,您需要非常小心共享變量并在更改之前獲取鎖定.

4)您應(yīng)該在主線程中捕獲KeyboardInterrupt異常,并找到一種方法與您的其他線程進行通信以終止:)

5)使用小寫方法名稱,因此不是getUserInput,而是調(diào)用get_user_input.使用大寫的類名并從object繼承:class Test(object):

這是一個運行的例子:

import threading
from time import sleep


def main():
    t = Test()
    t.go()
    try:
        join_threads(t.threads)
    except KeyboardInterrupt:
        print "\nKeyboardInterrupt catched."
        print "Terminate main thread."
        print "If only daemonic threads are left, terminate whole program."


class Test(object):
    def __init__(self):
        self.running = True
        self.threads = []

    def foo(self):
        while(self.running):
            print '\nHello\n'
            sleep(2)

    def get_user_input(self):
        while True:
            x = raw_input("Enter 'e' for exit: ")
            if x.lower() == 'e':
               self.running = False
               break

    def go(self):
        t1 = threading.Thread(target=self.foo)
        t2 = threading.Thread(target=self.get_user_input)
        # Make threads daemonic, i.e. terminate them when main thread
        # terminates. From: https:///a/3788243/145400
        t1.daemon = True
        t2.daemon = True
        t1.start()
        t2.start()
        self.threads.append(t1)
        self.threads.append(t2)


def join_threads(threads):
    """
    Join threads in interruptable fashion.
    From https:///a/9790882/145400
    """
    for t in threads:
        while t.isAlive():
            t.join(5)


if __name__ == "__main__":
    main()

鍵入e或E時,程序會在短暫延遲后結(jié)束(按照您的意圖).按ctrl c時,它會立即終止.制作一個使用線程響應(yīng)異常的程序比預(yù)期的要復(fù)雜一些.我在上面的源代碼中包含了重要的參考資料.

這是它在運行時的樣子:

$python supertest.py

Hello

Enter 'e' for exit: 
Hello


Hello


Hello

e
$
來源:http://www./content-1-216201.html

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多