0
如何在功能send
不發送參數時如何將receive
功能設置爲print "waiting"
?在等待來自其他功能的值時打印「正在等待」功能
嗯,我真的不知道我該怎麼辦呢,我想到了join()
方法,但我想這一點:
import threading
import random
waiting = True
def receive(a=""):
while waiting:
print "[receive] waiting for args"
print "[receive] Args received: %s" % a # args received from send function
def send(args):
global waiting
if waiting:
if random.randint(1,3) == 2:
waiting = False
print "[send] Args sent"
receive(a=args) # send the args
fargs = ["hello, world", "foo", "bar", "foobar", 12]
t1 = threading.Thread(target=receive, args=[])
t2 = threading.Thread(target=send, args=[fargs])
t1.start()
t2.start()
有時候這工作,但有時我在一個無限循環獲取。
@EDIT
現在它工作正常:
import threading
import random
waiting = True
def receive(a=""):
while waiting:
print "[receive] waiting for args"
if a:
print "[receive] Args received: %s" % a
def send(args):
global waiting
while waiting:
if random.randint(1,3) == 2:
waiting = False
print "[send] Args sent"
receive(a=args)
fargs = ["hello, world", "foo", "bar", "foobar", 12]
t1 = threading.Thread(target=receive, args=[])
t2 = threading.Thread(target=send, args=[fargs])
t1.start()
t2.start()
有沒有更好的辦法做到這一點?
對不起,我的英語。
_「有時我會陷入無限循環。」_對我有意義。當'random.randint'不等於2時,'send'永遠不會發送任何東西,所以'receive'永遠循環。你期望發生什麼? (順便說一句,你可能不需要在'send'中調用'receive',因爲'receive'的一個實例已經在運行了) – Kevin
對不起,我的錯誤。我編輯了這篇文章。 –