从最慢的线程或从更快的线程激活线程
Activate threads from the slowest or from the faster?
我在i7上的Linux上有一个使用boost::thread
的应用程序,目前我有大约10个线程(在8个内核之间)同时运行,对大约240 x 180
到960 x 720
大小的图像进行图像处理,因此较小的图像自然比较大的图像完成得更快。在未来的某个时候,我可能需要增加线程的数量,这样肯定会有比核心多得多的线程。
那么,是否有一条经验法则来决定启动和等待线程的顺序;最快的先把小任务排除在外,还是最慢的先把它开始得更快,所以完成得更快?还是我的同步代码不稳定?
作为参考,我的代码大约是这样的,其中编号较低的线程较慢:
Globals
static boost::mutex mutexes[MAX_THREADS];
static boost::condition_variable_any conditions[MAX_THREADS];
主螺纹
// Wake threads
for (int thread = 0; thread < MAX_THREADS; thread++)
{
mutexes[thread].unlock();
conditions[thread].notify_all();
}
// Wait for them to sleep again
for (int thread = 0; thread < MAX_THREADS; thread++)
{
boost::unique_lock<boost::mutex> lock(mutexes[thread]);
}
正在处理线程
static void threadFunction(int threadIdx)
{
while(true)
{
boost::unique_lock<boost::mutex> lock(mutexes[threadIdx]);
// DO PROCESSING
conditions[threadIdx].notify_all();
conditions[threadIdx].wait(lock);
}
}
多亏了评论者的提示和大量的谷歌搜索,我已经完全重新编写了我的代码,在没有互斥的情况下,速度似乎稍微快一些。
Globals
// None now
主螺纹
boost::asio::io_service ioService;
boost::thread_group threadpool;
{
boost::asio::io_service::work work(ioService);
for (size_t i = 0; i < boost::thread::hardware_concurrency(); i++)
threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &ioService));
for (int thread = 0; thread < MAX_THREADS; thread++)
ioService.post(std::bind(threadFunction, thread));
}
threadpool.join_all();
正在处理线程
static void threadFunction(int threadIdx)
{
// DO PROCESSING
}
(我把它做成了一个社区Wiki,因为它不是我真正的答案。)
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在C++中使用cURL和多线程
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在cuda线程之间共享大量常量数据
- 如何将元素添加到数组的线程安全函数?
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 异常属于C++中的线程还是进程
- C++中的线程安全删除
- C++使用params创建线程函数会导致转换错误
- 类与私有变量的其他类之间的线程安全性
- CoInitialize()在单独的线程上崩溃而不返回
- c++中的线程池
- 线程之间的布尔停止信号
- 为什么std::async使用同一个线程运行函数
- C++挂起线程,然后通过其他线程重新激活
- 从最慢的线程或从更快的线程激活线程
- QT小部件插槽调用没有被单独的线程信号激活