问题
Consider I have a one-thread code that does something in the main thread and it takes about 10-20 ms. I would like to utilize two cores of my processor and split the task for two threads living at different cores. Technically I should probably resume two sleeping threads and make myself to sleep until they're done and sleep again. Nothing scaring if the task is long enough to execute. But for 10-20 ms I suspect the penalty of using well-known synchronization techniques would cost me a large share of time. If I'm too suspicious and the Windows/CPU does good job making all sleeping/waking requests effective, then what is the smallest time it still makes sense to split, 1ms, 10ms, 100ms?
回答1:
Multi-threading using an existing threadpool (existing sleeping threads) can speed up a 10-20ms operation.
The specific synchronization calls to wake up the threads and join them are miniscule, far less than 1ms.
One thing to be aware of is locality of reference. If the code running on multiple threads is accessing the same memory, then the CPUs will have to synchronize memory access which could reduce the actual performance improvement.
Equally if the threads are using common resources and require locking or other thread synchronization, waiting on these locks would degrade performance.
If there is any I/O in these threads, then splitting it into threads will help speed it up the most.
回答2:
Unless this short task is called a lot of times (i.e. in a loop) there is no point because at best you are going to save yourself 10ms processing time even before you account for any task switching/thread starting/syncing...
回答3:
If your have many tasks and your working threads continuously take tasks from common queue (like in ExecutorService), overhead for a task is 1..10 microseconds. Fork/Join facility is even more effective. Thread switching is most expensive action, so instead of resuming 2 sleeping threads and making master thread to wait, better run one task on master thread and only one on the worker thread.
来源:https://stackoverflow.com/questions/12196961/is-it-possible-to-use-multi-threading-effectively-for-a-short-period-of-time