简体   繁体   English

线程池的同步

[英]Synchronizing of Threadpool

In every time step multiple worker threadss W[1..10] are supposed to idle until they are signaled from the main thread to start working.在每个时间步中,多个工作线程 W[1..10] 应该空闲,直到它们从主线程发出信号开始工作。 Do each their work, Signal back to the mainthread that they are done and return to the waiting state they were in before.完成他们的每一项工作,向主线程发信号通知他们已经完成并返回到他们之前处于的等待状态。 The mainthread is supposed to be waiting while the workerthreads do their work.主线程应该在工作线程完成工作时等待。

I was trying to do this using std::condition_variable ann std::mutex but failed.我试图使用std::condition_variable std::mutex来做到这一点,但失败了。 What is the right approach to the problem not using boost or other high Level libraries?不使用 boost 或其他高级库解决问题的正确方法是什么? I would like to avoid spawning and joining threads in every step for performance reasons.出于性能原因,我想避免在每个步骤中生成和加入线程。 Thank you very much.非常感谢。

Edit:编辑:

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 << "exit\n";
            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;
}

something like就像是

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

main thread will wait until threads 1..3 finish working;主线程将等到线程 1..3 完成工作; and those threads will be working simultaneously这些线程将同时工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM