我是线程的新手。我正在使用 4 个线程在 4 个不同的事物上运行我的函数。现在我需要在我的函数中设置一个标志,它会对每个函数进行不同的计算。最好的方法是什么? 我正在尝试这样做,这是正确的吗?如果有更好的方法请提出。
def func(i,flag):
while True:
if flag==0:
something
else:
something else
flag-=1
flag=["0","0","0","0"]
try:
thread.start_new_thread( func, (10,flag[0], ) )
thread.start_new_thread( func, (11,flag[1], ) )
thread.start_new_thread( func, (12,flag[2], ) )
thread.start_new_thread( func, (13,flag[3], ) )
except:
print "Error: unable to start thread"
#after sometime
flag[0]+=1
flag[2]+=1
请您参考如下方法:
我看到以下问题:
- 使用
threading而不是thread。thread在 Python3 中消失了。 - 您将
flag初始化为一个字符串列表,然后通过加 1(整数)来递增每个元素。那行不通。 - 线程对全局变量
flag没有可见性。 “一段时间后”对列表所做的更改不会影响func中的局部变量flag。它们是两个不同的对象。修改列表元素不会更改最初传递给func的值,因为它是一个简单的字符串; Python 中的字符串具有值(而非引用)语义。
尝试以下操作:
flag=[0,0,0,0]
def func(i,thread_index):
if flag[thread_index] == 0:
something
else:
something else
flag[thread_index] -= 1
try:
thread.start_new_thread( func, (10,0))
thread.start_new_thread( func, (11,1))
thread.start_new_thread( func, (12,2))
thread.start_new_thread( func, (13,3))
except:
print "Error: unable to start thread"
#after sometime
flag[0] += 1
flag[2] += 1
这是一个相当粗糙但它做你想要的。 flag 是一个全局列表,每个线程访问该列表中的唯一索引。当主线程访问列表时,您会看到 func 发生变化,因为它通过封闭的容器(列表)对象访问每个元素。
