Pausing execution of a Thread WITHOUT sleeping?

橙三吉。 提交于 2019-12-12 09:05:50

问题


I am using the Skype API, which sends back a message everytime it receives one. I am not sure if this really is what is causing it, but it's the closest I can get: When I send too many messages, the COM control can't handle all the replies, which causes it to crash the whole app. That happens when I use a for loop.

I am using Threads to do the job, so my program won't hang. I know I can do Sleep(); in the thread, and will (should) not make the whole program sleep. The problem is though, that my COM control will be sleeping aswell, so it still wont be able to process whatever it needs, so it can keep up again.

So, the question is: How can I pause the routine without pausing the whole thread, so that the replies can be processed by my COM object, without overloading?


回答1:


CoWaitForMultipleHandles can be used to block the thread, but still pump COM messages (in case of STA), some other Windows messages and has a timeout. Sounds like something you could use.




回答2:


I tend to use TSimpleEvent for such cases. It may block your thread for a set amount of time (the time-out), but you may also wake up your thread with it externally (e.g. right before your call Terminate). It doesn't cost CPU. It may be deblocked by calls from other threads. I use this for threads that have to behave as if they are timed, e.g. wake up every 5 seconds and do something.

*) I Don't grasp your exact problem, but pausing in threads without sleeps is what I answered to. Maybe it can be used as (part of) your solution. Good luck with it.




回答3:


Sounds like the thread needs to test whether it should send a message each time it is called, rather than always sending one.

How to do this depends on the implementation; you may have some kind of condition that needs to be met (a size threshold, so you never send a message that is trivially small), or perhaps through rate limiting (check whether the last message sent long enough ago that you can afford to send another).

I hope this is helpful; I know it is very high-level.




回答4:


Could you use two threads, one for sending, one for receiving, and lock them like in this consumer/producer example ("Thread Synchronization with Guarded Blocks in Delphi", for Delphi 2009 and higher), so that a new message can only be sent by the producer when the consumer has processed it?



来源:https://stackoverflow.com/questions/5396174/pausing-execution-of-a-thread-without-sleeping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!