The following code often freezes when I compile/run it using GCC 12.2.0
#include <iostream>
#include <latch>
#include <thread>
#include <vector>
int main() {
for(unsigned k = 0; k != 10; k++) {
std::latch sync{2};
auto task = [&sync]() { sync.arrive_and_wait(); };
std::thread t1(task);
std::thread t2(task);
t1.join(); std::cout << k << ":1" << std::endl;
t2.join(); std::cout << k << ":2" << std::endl;
}
}
If I remove sync.arrive_and_wait()
then everything is fine.
The last line of outputs I saw in multiple runs that led to deadlock are:
2:1
, 1:2
, 0:2
, ...
Isn't this code supposed to be deadlock-free?