mardi 26 avril 2022

c++ std::atomic concurrency printing

Hello everyone I have a code for threads to print their number and number that they are counting:

void print_num_n_times(std::uintmax_t thread_num, std::uintmax_t num_times_to_print = 100)
{
    static std::atomic_bool is_printing{ false };
    std::uintmax_t i = 0;
    while (i < num_times_to_print)
    {
        //if the thread is not acquired.
        while (is_printing.load());
        //if the thread previous value was false (maybe another thread was intterupting.
        if (!is_printing.exchange(true)) {
            std::cout << "Output from thread " << thread_num << " Value: " << i + 1 << '\n';
            is_printing.exchange(false);
            i++;
        }
    }
}

and this is the only solution I have found for multiple threads to print nicely like this (2 threads count to 5):

Output from thread 2 Value: 1
Output from thread 2 Value: 2
Output from thread 2 Value: 3
Output from thread 2 Value: 4
Output from thread 2 Value: 5
Output from thread 1 Value: 1
Output from thread 1 Value: 2
Output from thread 1 Value: 3
Output from thread 1 Value: 4
Output from thread 1 Value: 5

Is there a better solution, because it's slow and I feel like there could be a better solution. Any help would be appreciated!

Aucun commentaire:

Enregistrer un commentaire