线程池的同步

Synchronizing of Threadpool

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

在每个时间步骤中,多个工作线程W[1..10]应该是空闲的,直到它们从主线程收到开始工作的信号。完成他们的每一项工作,向主线程发出完成的信号,并返回到以前的等待状态。主线程应该在等待,而workersreads正在做他们的工作。

我曾尝试使用std::condition_variablestd::mutex来完成此操作,但失败了。对于不使用boost或其他高级库的问题,正确的方法是什么出于性能原因,我希望避免在每一步中生成和连接线程非常感谢。

编辑:

const size_t thread_num = 10;
int busy_count = thread_num;
std::condition_variable cv;
std::mutex cv_m;
std::condition_variable cv_lock1;
std::mutex cv_m_lock1;

bool lock_1;
bool end_all = false;
void wthread()
{   
    do {        
        {
            std::unique_lock<std::mutex> lk(cv_m_lock1);
            cv_lock1.wait(lk, []{return lock_1 == false; });
        }
        if (end_all)
        {
            std::cout << "exitn";
            return;
        }
        // do work
        {           
            std::lock_guard<std::mutex> lk(cv_m);
            busy_count--;
            std::cout << busy_count << " ";         
        }       
        cv.notify_all();
        {
            std::unique_lock<std::mutex> lk(cv_m_lock1);
            cv_lock1.wait(lk, []{return lock_1 == true; });
        }

    } while (true);
}
int _tmain(int argc, _TCHAR* argv[])
{       
    std::thread *t[thread_num];
    lock_1 = true;
    for (unsigned int i = 0; i < thread_num; i++)
        t[i] = new std::thread(wthread);
    for (int i = 0; i < 10; i++)
    {
        busy_count = 10;            
        lock_1 = false;     
        cv_lock1.notify_all();      
        {
            std::unique_lock<std::mutex> lk(cv_m);
            cv.wait(lk, []{return busy_count == 0; });
        }
        lock_1 = true;      
        cv_lock1.notify_all();
    }
    end_all = true;
    lock_1 = false; 
    cv_lock1.notify_all();  

    for (unsigned int i = 0; i < thread_num; i++)
        t[i]->join();
    return 0;
}

类似的东西

std::thread thread1([](){/*do something*/});
std::thread thread2([](){/*do something*/});
std::thread thread3([](){/*do something*/});
thread1.join();
thread2.join();
thread3.join();

主线程将等待线程1..3完成工作;并且这些线程将同时工作