简体   繁体   English

新线程中的Python对象方法

[英]Python object method in a new thread

I have an object instantiated in the main thread and i wish to run one of it's methods in a different thread asynchronously . 我在主线程中实例化了一个对象,并且希望在另一个线程中异步运行它的方法之一。 Here is the code i used: 这是我使用的代码:

obj = self._collection[index]
t1 = threading.Thread( target = obj.foo() )
t1.start()

The method does execute but it is in sync with the main thread. 该方法确实执行,但是与主线程同步。

Use t1 = threading.Thread( target = obj.foo ) instead. 请改用t1 = threading.Thread( target = obj.foo )

In this case, the Thread constructor is expecting a reference to a function...when you pass it obj.foo() , you are passing it the result of the foo() function. 在这种情况下, Thread构造函数期待一个函数的引用......当你通过它obj.foo()你向它传递的结果 foo()函数。 That's not what you want! 那不是你想要的! Pass a reference to the function. 将引用传递给该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM