Print Alternating Numbers in Sequence with Multi-threading

From Software Engineers Wiki
Jump to: navigation, search

Write multi-threaded code in C++ so that one thread prints all even numbers and other all odd numbers with the output always in sequence.

Answer #1

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

static std::mutex mutex_for_even_ready, mutex_for_odd_ready;
static volatile bool do_print_even = false, do_print_odd = true;
static std::condition_variable cv_even_ready, cv_odd_ready;

void print_odd(unsigned int max)
{
        unsigned int start = 1;

        if (start > max)
                return;

        for (;;) {
                {
                        std::unique_lock<std::mutex> lock(mutex_for_odd_ready);
                        cv_odd_ready.wait(lock, []() { return do_print_odd; });
                        do_print_odd = false;
                }

                std::cout << start << " ";

                {
                        std::unique_lock<std::mutex> lock(mutex_for_even_ready);
                        do_print_even = true;
                        cv_even_ready.notify_one();
                }

                start += 2;
                if (start > max)
                        return;

        }
}

void print_even(unsigned int max)
{
        unsigned int start = 2;

        if (start > max)
                return;

        for (;;) {
                {
                        std::unique_lock<std::mutex> lock(mutex_for_even_ready);
                        cv_even_ready.wait(lock, []() { return do_print_even; } );
                        do_print_even = false;
                }

                std::cout << start << " ";

                {
                        std::unique_lock<std::mutex> lock(mutex_for_odd_ready);
                        do_print_odd = true;
                        cv_odd_ready.notify_one();
                }

                start += 2;
                if (start > max)
                        return;

        }
}

int main(void)
{
        const unsigned int max = 1000;

        std::thread thread_odd(print_odd, max);
        std::thread thread_even(print_even, max);

        thread_odd.join();
        thread_even.join();

        std::cout << std::endl;

        return 0;
}
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox