功能打印“等待”,同时等待另一个功能的值

时间:2014-04-14 18:08:20

标签: python multithreading

如果函数receive没有发送参数,如何将print "waiting"函数发送到send

好吧,我真的不知道怎么做,我想到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()

有更好的方法吗?

抱歉我的英文。

1 个答案:

答案 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)

我没有对它进行过多的测试,所以它可能有一些错误,而且我不是线程专家,因此我不知道是否应该这样做,但我希望它可以帮助某人。当pandas从sql DB下载数据时,我用它来打印点。