开发者

How does Timer in Python work, regarding multithreading? [duplicate]

This question already has answers here: How Python threading Timer work internally? (2 answers) Closed 2 months ago.

If I call

Timer(.1, some_function, [some_arguments]).start()

multiple times, what exactly happens behind the scenes?

The source of our problem is ...

We have a method that's essentially:

def move(target):
 force = calculateForce(target-getCurrentPosition())
 if(force != 0)
   setForce(force)
   Timer(.1, moveCursor, [tx]).start()
 else:
   setForce(0)

After setting the force, we need to check after a certain amount of time whether it should be stopped. (This information is to/from an external physical device that doesn't fire events.)

There's weird issues 开发者_开发百科in how much time this function is taking, and also we're getting "can't start new thread" errors after a certain amount of time.

This leads me to believe that Timer(...) does not reuse threads but creates a new one every time.

Combined with a belief that the library we're using isn't threadsafe, these errors would make some sense....


Right: each call to Timer does start a new thread. Indeed, class threading.Timer is documented as being "a thread". You can confirm this by reading the source code, line 707.

A good alternative is to run a scheduler in a single thread, receiving requests through a Queue.Queue instance (intrinsically threadsafe) and intrinsically serializing them (which may also take care of your "non-thread-safe-library" problems without needing further locking or synchronization, depending how you arrange your overall architecture of course).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜