2016-10-21 19 views
0

看看這段代碼創建MUL-線程:Python3.4一個任務大約

def w(i): 
    print("%s start" % i) 
    time.sleep(10) 
    print("end %s waiting" % i) 


class ss(threading.Thread): 
    def __init__(self, i): 
     threading.Thread.__init__(self) 
     self.i = i 

    def run(self): 
     print("%s start" % self.i) 
     time.sleep(10) 
     print("end %s waiting" % self.i) 

c=ss("c") 
c.start() 
d=ss("d") 
d.start() 

threading.Thread(w("a")).start() 
threading.Thread(w("b")).start() 

的結果是這樣的:

c start 
a start 
d start 
end c waiting 
end a waiting 
end d waiting 
b start 
end b waiting 

也許你已經知道我的puzzle.I通過創建線程「 threading.Thread」的功能,它不能運行synchronously.Is它全局函數僅僅只有一個線程運行一次?我用python3.4

回答

1
threading.Thread(w("a")).start() 

意味着EXECUT e w("a")並將結果傳遞給threading.Thread()構造函數。而不是傳遞可調用的對象,而是調用它。你需要分開函數和它的參數:

threading.Thread(target = w, args = ["a"]).start() 
+0

謝謝。這就是原因。 –