Consider the following C++ code:
#include <barrier>
#include <iostream>
#include <string>
#include <thread>
int main()
{
constexpr unsigned N = 2;
std::barrier barrier(N);
auto const run = [&barrier]()
{
std::string buff;
for(unsigned i = 0; i < 1000; i++)
{
std::cout << ((buff = "A ") + std::to_string(i) + "\n");
barrier.arrive_and_wait();
std::cout << ((buff = "B ") + std::to_string(i) + "\n");
barrier.arrive_and_wait();
std::cout << ((buff = "C ") + std::to_string(i) + "\n");
}
};
std::thread ts[N];
for(unsigned j = 0; j < N; j++) ts[j] = std::thread(run);
for(unsigned j = 0; j < N; j++) ts[j].join();
}
When I compile/run it using Clang 12.0.1
it behaves as expected.
Same expected behavior when I use GCC 11.1 (C++ 20)
available online at en.cppreference.com.
However, when I use my local GCC 11.1.0
, it often deadlocks after printing the following lines:
A 0
A 0
B 0
B 0
C 0
A 1
- Is this code well-defined?
- Is it supposed to be deadlock-free?