How I can run two threads parallelly one by one?

Solution 1:

Assuming you have a valid use case for using two threads like this, here is an example. I prefer using std::async over std::thread it has better abstraction and information exchange with the main thread. The example is written for 2 threads but can easily be changed to more threads.

Live demo here : https://onlinegdb.com/eQex9o_nMz

#include <future>
#include <condition_variable>
#include <iostream>

// Setup a helper class that sets up
// the three things needed to correctly
// use a condition variable
// 1) a mutex
// 2) a variable
// 3) a condition_variable (which is more of a signal then a variable)
//
// also give this class some functions
// so the the code becomes more self-explaining

class thread_switcher_t
{
public:
    void thread1_wait_for_turn()
    {
        std::unique_lock<std::mutex> lock{ m_mtx };
        m_cv.wait(lock, [&] {return (thread_number==0); });
    }

    void thread2_wait_for_turn()
    {
        std::unique_lock<std::mutex> lock{ m_mtx };
        m_cv.wait(lock, [&] {return (thread_number==1); });
    }

    void next_thread()
    {
        std::unique_lock<std::mutex> lock{ m_mtx };
        thread_number = (thread_number + 1) % 2;
        m_cv.notify_all();
    }

private:
    std::size_t thread_number{ 0 };
    std::mutex m_mtx;
    std::condition_variable m_cv;
};


int main()
{
    thread_switcher_t switcher;
    
    auto future1 = std::async(std::launch::async, [&]
    {
        for(std::size_t n = 0; n <= 100; n+=2)
        {
            switcher.thread1_wait_for_turn();
            std::cout << "thread 1 : " << n << "\n";
            switcher.next_thread();
        }
    });

    auto future2 = std::async(std::launch::async, [&]
    {
        for (std::size_t n = 1; n <= 100; n += 2)
        {
            switcher.thread2_wait_for_turn();
            std::cout << "thread 2 : " << n << "\n";
            switcher.next_thread();
        }
    });

    future1.get();
    future2.get();

    return 0;
}