vendredi 21 février 2020

Is the following code a good solution for a multi-threaded increment counter and print?

Can you give you your opinion, please? What would you do differently? I mean, do you think it would be better if I have done it with std::task or std::mutex, std::condition_variable, etc? I an overkill to control the threads with 2 flags?

std::atomic<int> counter = { 0 };
std::atomic<bool> switchFlag = { false };
std::atomic<bool> finished = { false };
constexpr int MAX_NUM = 10;

void increment(){
    while (!finished.load()){
        if (!switchFlag.load()){
            std::cout << "incremented to =" << ++counter << '\n';
            switchFlag.store(true);
        }
    }
}

void print(){
    while (!finished.load()) {
        if (switchFlag.load()){
            std::cout << "counter=" << counter.load() << '\n';
            if (counter.load() >= MAX_NUM)
                finished.store(true);

            switchFlag.store(false);
        }
    }
}

int main() {
    auto t1 = std::thread(increment);
    auto t2 = std::thread(print);
    t1.join();
    t2.join();
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire