mardi 29 octobre 2019

Notify_one doesn't choose random thread, as intended

Thanks for advance for any help. Trying to make a program that would create 6 threads, then each 2 seconds randomly choose one and make it print its number. I am obviously doing something wrong, because it just keeps printing 0-1-2-3-4-5 endlessly. Here's the code:

#include <thread>
#include <memory>
#include <chrono>
#include <condition_variable>
std::condition_variable* cv = new std::condition_variable();
std::mutex cv_m;

void threadFunc(std::shared_ptr<bool> flag2, int id)
{
    while (true)
    {
        std::unique_lock<std::mutex> lock(cv_m);
        cv->wait(lock);
        if (true)
            if (*flag2) std::cout << "Thread" << " " << id << std::endl;
    }
}
int main() {

    std::shared_ptr<bool> f2 = std::make_shared<bool>(false);

    std::thread threads[6];

    for (int i = 0; i < 6; i++)
        threads[i] = std::thread(threadFunc, f2, i);
    *f2 = true;

    while (true)
    {
        cv->notify_one();
        std::this_thread::sleep_for(std::chrono::seconds(2));
    }

    return 0;
}```



Aucun commentaire:

Enregistrer un commentaire