lundi 27 avril 2020

condition variables output

I'm trying to use condtion_variable to execute (phase j) 10 times and then execute the done 10 times after all (phase j) is executed.

#include <iostream>
#include <condition_variable>
#include <random>
#include <mutex>
#include <chrono>
#include <string>

int num_threads = 10;
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
std::default_random_engine e;
std::uniform_int_distribution<> id(1, 2000);

void thread(std::string s) {


            std::unique_lock<std::mutex> ul(mtx);
            std::this_thread::sleep_for(std::chrono::milliseconds(id(e)));
            std::cout << "phase j " << std::endl;
            cv.wait(ul, [] { return ready; });



            std::this_thread::sleep_for(std::chrono::milliseconds(id(e)));

            std::cout << s << " is done" << std::endl;
            std::lock_guard<std::mutex> lg(mtx);
            ready = true;
            cv.notify_all(); 


}

int main()
{

    std::vector<std::thread> mythreads;
    for (int i = 0; i < num_threads; i++) {
        mythreads.push_back(std::thread(thread, std::to_string(i)));
    }


    for (auto& t : mythreads)
        t.join();

}

my output after trying to use condition_variable enter image description here

without adding to the main, how I can use condition_variable to make it work.

Aucun commentaire:

Enregistrer un commentaire