【发布时间】: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