【问题标题】:Reading the results from an infinite loop using threads in python使用python中的线程从无限循环中读取结果
【发布时间】:2014-03-10 08:32:40
【问题描述】:

我目前正在 Windows 8 上使用 python v.2.7。

我的程序正在使用线程。线程在无限时间内执行名为getData() 的方法,该方法执行以下操作:

  • 使当前线程休眠一段时间
  • 调用compareValues()
  • compareValues() 中检索信息并将它们添加到 列表名为myList

compareValues() 执行以下操作:

  • 生成一个随机数
  • 检查是否小于 5 或​​大于或等于 5 并产生结果以及当前线程的名称

我将这些线程的结果保存到一个名为myList 的列表中,然后最后打印这个myList

问题getData() 无限循环。如何访问myList 以检索结果?在这种情况下,什么是好方法。 如果您删除 while True:,则程序可以正常工作。

代码

import time
from random import randrange
import threading

myList = []
def getData(i):
   while True:
        print "Sleep for %d"%i
        time.sleep(i)
        data = compareValues()
        for d in list(data):
            myList.append(d)

def compareValues():
        number = randrange(10)
        name = threading.current_thread().name
        if number >= 5:
             yield "%s: Greater than or equal to 5: %d  "%(name, number)
        else:
             yield "%s: Less than 5: %d  "%(name, number)

threadList = []
wait = randrange(10)+1
t = threading.Thread(name = 'First-Thread', target = getData, args=(wait,))
threadList.append(t)
t.start()
wait = randrange(3)+1
t = threading.Thread(name = 'Second-Thread', target = getData, args=(wait,))
threadList.append(t)
t.start()
for t in threadList:
    t.join()
print "The final list"
print myList

感谢您的宝贵时间。

【问题讨论】:

  • 为什么要getData()方法无限循环?
  • 这是我现实世界问题的一个例子。在我的现实世界问题中,我必须每 5 秒左右从服务器读取一些不同的值并分别更新我的旧值。所以,我想无限地从服务器读取值。我只是试图将我的现实世界问题转换为这个虚拟问题。 :)

标签: python multithreading python-2.7 thread-safety


【解决方案1】:

我发现一些不一致的地方可能有助于使代码看起来更清晰一些。例如:

  1. compareValues() 应该返回'字符串格式的结果......'而不是屈服。我对吗?因为这个函数一次只计算一个值。
  2. getData() 应如下所示:

    def getData(i):
        while True:
            print "Sleep for %d"%i
            time.sleep(i)
            myList.append(compareValues())
    

原因和我上一点说的完全一样。

P.S.:我不知道为什么代码格式不正确。对不起... :-(

希望对你有帮助!

【讨论】:

  • 是的,您的建议提供了一些提示,帮助我通过修改代码来解决问题。
  • 太棒了!我很高兴。
猜你喜欢
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 2014-05-30
  • 1970-01-01
  • 1970-01-01
  • 2018-07-03
  • 2018-09-01
  • 2019-11-25
相关资源
最近更新 更多