Python 功能打印“;“等待”;等待另一个函数的值时
当函数Python 功能打印“;“等待”;等待另一个函数的值时,python,multithreading,Python,Multithreading,当函数send不发送参数时,如何执行receive函数打印“waiting” 嗯,我真的不知道怎么做,我考虑了join()方法,但我尝试了以下方法: import threading import random waiting = True def receive(a=""): while waiting: print "[receive] waiting for args" print "[receive] Args received: %s" % a #
send
不发送参数时,如何执行receive
函数打印“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()
有时这是可行的,但有时我会陷入无限循环
@编辑
现在它可以正常工作了:
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()
有更好的方法吗
对不起,我的英语很差。我知道这个线程已经很旧了,但是通过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)
def count_直到_超时(超时):
开始时间=time.time()
n=0
while time.time()-开始时间<超时:
n+=1
返回n
n=DotsPrinter()。在执行时打印点(计数直到超时,5)
打印(n)
我没有立即测试它,所以它可能有一些错误,我不是线程专家,因此我不知道这样的事情是否应该做,但我希望它能帮助别人。熊猫从sql数据库下载数据时,我用它来打印点。“有时我会陷入无限循环。”对我来说很有意义。当
random.randint
不等于2时,则send
从不发送任何内容,因此receive
将永远循环。你预计会发生什么?(顺便说一下,您可能不需要在send
中调用receive
,因为receive
的实例已经在运行)对不起,我的错误。我编辑了这篇文章。