从最慢的线程或从更快的线程激活线程

Activate threads from the slowest or from the faster?

本文关键字:线程 激活      更新时间:2023-10-16

我在i7上的Linux上有一个使用boost::thread的应用程序,目前我有大约10个线程(在8个内核之间)同时运行,对大约240 x 180960 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,因为它不是我真正的答案。)