python - 如何将对象列表传递给线程函数

标签 python multithreading

我必须将对象列表传递给在 python 线程中执行的函数。我需要能够调用这些对象的函数,例如 animal.bite()。我创建了一个通用测试类:

class test_class:    
    def f(self):
        print 'hello'

并创建了这些对象的列表:

test_object = test_class()
new_object = test_class()
strlist = [test_object, new_object]

并且有一个函数,如果线程还没有被创建,它会创建一个线程:

def threadScheduler(*stringlist):
    global lock #variable defined elsewhere, makeshift resource lock
    if not lock:
        print "creating thread"
        lock = True
        thread = threading.Thread(name='heartbeat', target=threadWorkLoad, args=(stringlist,))
        thread.start()

这是函数threadWorkLoad:

def threadWorkLoad(*stringlist):
    global lock
    for item in stringlist:
        print 'in thread', item.f()
    time.sleep(2)
    lock = False
    return

这是主循环:

for x in range(0,10):
    print 'in main thread', strlist[0].f()
    threadScheduler(strlist)
    time.sleep(1)

我想做的是能够在 threadWorkLoad 中的列表中的对象上调用函数 f(),但目前我得到错误 AttributeError: 'tuple' 对象没有属性 'f'

如果我用字符串替换这些对象,代码就会按照我想要的方式工作。但我需要能够对对象做同样的事情。我如何在 Python 中执行此操作?

编辑:

我试过的其他一些东西-

我将 threadScheduler 中的线程创建更改为 thread = threading.Thread(name='heartbeat', target=threadWorkLoad, args=[stringlist])没有运气。

我还尝试将以下语句作为 threadScheduler 的第一行:

print 'in scheduler', stringlist[0].f()

我得到了同样的错误。问题似乎与将列表对象作为函数参数传递有关。

我还应该澄清一下,我们使用的是 Python 2.5.2。

最佳答案

必须进行两项更改才能使其生效(感谢 Scott Mermelstein):

在主循环中,threadScheduler(strlist) 必须更改为 threadScheduler(*strlist)。我通过将以下行添加到 threadScheduler() 函数来验证这一点:

print 'in scheduler', stringlist[0].f()

只有在我添加星号后才能成功调用f()。不过,我不确定为什么必须以这种方式传递论点。

此外,我必须改变

thread = threading.Thread(name='heartbeat', target=threadWorkLoad, args=(stringlist,))

thread = threading.Thread(name='heartbeat', target=threadWorkLoad, args=tuple(stringlist))

然后我能够在 threadWorkLoad() 函数中为列表中的每个对象成功调用 f()

关于python - 如何将对象列表传递给线程函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39377862/

相关文章:

java - 线程服务器/客户端在第二个客户端加入后停止

python - 在requirements.txt中包含python版本吗?

python - 描述符 'date' 需要一个 'datetime.datetime' 对象,但收到一个 'unicode'

python - 是否可以通过 SSH 使用 os.walk?

c# - 在 C# 中使用数据库值填充 ConcurrentDictionary 的锁定注意事项

java - 通过java中的管道流丢失数据

multithreading - 线程安全的优先队列

c++ - 如何在 C++ 或 Winapi 中转移同步对象的所有权?

python - 子进程完成但仍未终止,导致死锁

python - 使用 dtreeviz 可视化决策树