educative.io

Cannor run the example code

Hello,

I am using a standard install of Ubuntu 23.04, where all the compiler are installed properly (I can compile and build most of my C++ codes).

However, I cannot compile the given examples codes in Concurrency class. My compiler cannot recognize ATOMIC_FLAG_INIT, even if I included and libraries.

I remember I had issues with execution policies, which I had to install TBB.

My question is, Is there any other library I need to install on my Ubuntu (e.g. TBB) to compile the example coded given in Educative.io? Anybody has experience on this?


Course: https://www.educative.io/courses/modern-cpp-concurrency-in-practice-get-the-most-out-of-any-machine
Lesson: https://www.educative.io/courses/modern-cpp-concurrency-in-practice-get-the-most-out-of-any-machine/mE2JEQ06lyp

Hi @Baris_Erkus !!
The issue you’re encountering with the code is related to the usage of ATOMIC_FLAG_INIT. In C++20, the ATOMIC_FLAG_INIT macro was removed, and it’s no longer necessary to initialize std::atomic_flag using this macro. Instead, you can directly initialize the std::atomic_flag variable with an empty initializer, which will set it to an unlocked state.

To fix the compilation issue, you can remove the ATOMIC_FLAG_INIT part from your code and modify the constructor as follows:

#include <iostream>
#include <atomic>
#include <thread>

class Spinlock {
    std::atomic_flag flag = ATOMIC_FLAG_INIT; // Directly initialize the atomic_flag.
public:
    void lock() {
        while (flag.test_and_set());
    }

    void unlock() {
        flag.clear();
    }
};

Spinlock spin;

void workOnResource() {
    spin.lock();
    // shared resource
    spin.unlock();
    std::cout << "Work done" << std::endl;
}

int main() {
    std::thread t(workOnResource);
    std::thread t2(workOnResource);

    t.join();
    t2.join();

    return 0;
}

With these modifications, your code should compile and run without any issues. The rest of the code is correct, and you don’t need to install any additional libraries like TBB to compile this specific code snippet. The std::atomic_flag is part of the C++ Standard Library and should be available in your standard C++ compiler.
I hope it helps. Happy Learning :blush: