2014-04-14 127 views
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() 

有沒有更好的辦法做到這一點?

對不起,我的英語。

+0

_「有時我會陷入無限循環。」_對我有意義。當'random.randint'不等於2時,'send'永遠不會發送任何東西,所以'receive'永遠循環。你期望發生什麼? (順便說一句,你可能不需要在'send'中調用'receive',因爲'receive'的一個實例已經在運行了) – Kevin

+0

對不起,我的錯誤。我編輯了這篇文章。 –

回答

0

我知道線程是相當古老的,但通過OP擴展自我的答案我創建了一個類,它在給定函數運行時打印一個字符串。

import threading 
import queue 
import time 
import getpass 

class DotsPrinter: 
    def __init__(self, float_dots_frequency=1, 
       string_to_print_while_waiting="."): 
    self.float_dots_frequency = float_dots_frequency 
    self.string_to_print_while_waiting = string_to_print_while_waiting 
    self.bool_waiting = True 
    self.output_queue = queue.Queue() 

    def print_dots(self): 
     if self.bool_waiting: 
      print("Waiting ", end="", flush=True) 
     while self.bool_waiting: 
      print(self.string_to_print_while_waiting, end="", 
        flush=True) 
      time.sleep(self.float_dots_frequency) 

    def function_wrapper(self, function, *args, **kwargs): 
     self.output_queue.put(function(*args, **kwargs)) 
     self.bool_waiting = False 

    def print_dots_while_executing(self, function, *args, **kwargs): 

     t1 = threading.Thread(target=self.print_dots) 
     t2 = threading.Thread(target=self.function_wrapper, args= 
           [function, *args], kwargs={**kwargs}) 
     t1.start() 
     t2.start() 
     return self.output_queue.get() 

的用法很簡單:

def count_till_timeout(timeout): 
    start_time = time.time() 
    n = 0 
    while time.time() - start_time < timeout: 
     n += 1 
    return n 

n = DotsPrinter().print_dots_while_executing(count_till_timeout, 5) 
print(n) 

我沒有測試它exstensively所以它可能有一些錯誤,我不是線程的專家,所以我不知道這樣的事情應該完成,但我希望它能幫助別人。我使用它來打印點,而大熊貓從SQL DB下載數據。