本文介绍了是否可以在短时间内有效地使用多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑我有一个单线程代码,它在主线程中执行某些操作,大约需要 10-20 毫秒.我想利用处理器的两个内核,并将任务拆分为位于不同内核的两个线程.从技术上讲,我可能应该恢复两个睡眠线程并让自己进入睡眠状态,直到它们完成并再次睡眠.如果任务足够长可以执行,没有什么可怕的.但是对于 10-20 毫秒,我怀疑使用众所周知的同步技术的代价会花费我大量的时间.如果我太怀疑并且 Windows/CPU 在使所有睡眠/唤醒请求有效方面做得很好,那么拆分 1ms、10ms、100ms 仍然有意义的最小时间是多少?

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?

推荐答案

使用现有线程池(现有休眠线程)的多线程可以加快 10-20 毫秒的操作.

Multi-threading using an existing threadpool (existing sleeping threads) can speed up a 10-20ms operation.

唤醒线程并加入它们的特定同步调用是微不足道的,远小于1ms.

The specific synchronization calls to wake up the threads and join them are miniscule, far less than 1ms.

需要注意的一件事是引用的位置.如果在多个线程上运行的代码正在访问相同的内存,那么 CPU 将不得不同步内存访问,这可能会降低实际的性能提升.

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.

如果这些线程中有任何 I/O,那么将其拆分为线程将有助于最大程度地加快速度.

If there is any I/O in these threads, then splitting it into threads will help speed it up the most.

这篇关于是否可以在短时间内有效地使用多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 19:06