printing odd and even number printing alternately using threads in C++

前端 未结 10 1162
后悔当初
后悔当初 2021-01-03 02:09

Odd even number printing using thread I came across this question and wanted to discuss solution in C++ . What I can think of using 2 binary semaphores odd and even semapho

10条回答
  •  轮回少年
    2021-01-03 03:09

    As a first thing, the two functions should a least contain a loop, (unless you just want a single number)

    A more standard solution (which remaps your idea) is to have a global structure containing a a mutex, and two condition variables (odd and even) plus a return value, and another condition for the printing. than use a uique_lock to handle the synchronization.

    IN PSEUDOCODE:

    struct global_t
    {
        mutex mtx;
        int value = {0};
        condition_variable be_odd, be_even, print_it;
        bool bye = {false};
    
        global_t() { be_odd.notify(); }
    } global;
    
    void odd_generator()
    {
        int my_odd = 1;
        for(;;)
        {
            unique_lock lock(global.mtx);
            if(global.bye) return;
            global.be_odd.wait(lock);
            global_value = my_odd; my_odd+=2;
            global.print_it.notify();
            if(my_odd > 100) bye=true;
        } //let RAII to manage wait states and unlocking
    };
    
    void even_generator()
    { /* same as odd, with inverted roles */ }
    
    void printer()
    {
        for(;;)
        {
            unique_lock lock(global.mtx);
            if(bye) return;
            global.ptint_it.wait(lock);
            std::cout << global.value << std::endl;
            ((global.value & 1)? global.be_even: global.be_odd).notify();
        }
    }
    
    
    int main()
    {
        thread oddt(odd_generator), event(even_generator), printt(printer);
        oddt.join(), event.join(), printer.join();
    }
    

    Note that, apart didactic purpose, this solution adds no value respect to a simple loop printing the value of a counter, since there will never be real concurrency.

    Note also (to avoid globals) that you can wrap everything into a class (making the actual main a class method) and instantate that class on the stack inside the new main.

提交回复
热议问题