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

前端 未结 3 849
遥遥无期
遥遥无期 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:43

    If the thread is truly waiting with something like a WaitForSingleObject, which uses no processor time, then times out, there is no reason to put a delay in the thread with sleep.

    Your user isn't waiting on the thread to be responsive, it's not using processor time, and other threads won't be blocked, so there would be no reason to put the thread to sleep.

    As David Heffernan indicated in his comment, if it's not using 100% of your CPU now, then there's no problem.

    You might use sleep() if you were single threaded and you had to occasionally respond to the user in between waiting on the serial port to respond.

    Also, having a thread sleep would not make it more efficient. It would simply yield processor cycles to other threads.

    Take a look at sleep(0) as a CPU efficient way of "wasting time" in a thread.

提交回复
热议问题