Hello. I study multithreaded programming and now I try to understand atomicity. In the example from the book by Anthony Williams, the atomic_flag structure has 2 overloaded methods.

bool test_and_set(memory_order _Order = memory_order_seq_cst) volatile noexcept; bool test_and_set(memory_order _Order = memory_order_seq_cst) noexcept; 

I created my structure and made the same overload. Here she is

 struct foo { bool test() volatile noexcept { cout << "volatile"; return true; } bool test() noexcept { cout << "No volatile"; return true; } }; 

When creating an object and calling the test () method, there is no ambiguity when calling. I do not understand why this is happening. Explain, please

When foo :: test () is called in the main thread, the main function calls the method without the volatile keyword.

  • one
    You seem to have declared the object of the foo class itself without a volatile qualifier. Therefore, there is no ambiguity. That is, for objects declared with the volatile qualifier, the corresponding method with volatile will be called. And for objects declared without this qualifier, another method will be called without a qualifier. - Vlad from Moscow

1 answer 1

The method with the volatile qualifier will be called for objects declared also with the volatile qualifier. Otherwise, the method without the volatile qualifier will be called.