What's the most CPU-efficient way to “waste time” in a thread?

前端 未结 3 866
遥遥无期
遥遥无期 2021-02-20 06:08

I have a number of threads (100\'s) that each execute for a few seconds at a time. When they are executing, they spend a significant amount of that time waiting for a response

3条回答
  •  不思量自难忘°
    2021-02-20 06:29

    The most efficient way to prevent a thread from using CPU time is to put it in a "wait mode."

    I don't use delphi at all, but it seems that the fundamentals for that are there. See "Chapter 11. Synchronizers and Events" and more specifically "Event simulation using semaphores".

    If you want to wait without using CPU, then use WaitForEvent:

    The signal state of the event is examined. If it indicates that the event is signalled, then the internal semaphore is signalled, and the count of threads blocked on the semaphore is decremented. The count of blocked threads is then incremented, and a wait is performed on the internal semaphore.

    If this is I/O related, then things work a little different. If it's a socket, then it might already be blocking, if it's asynchronous I/O, then you can use a semaphore and WaitForEvent and so on.

    In .NET there is the Monitor.Wait, Monitor.Signal, ManualResetEvent, CountDownLatch, etc., but I don't know what are the equivalent things in delphi.

提交回复
热议问题