4

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
  1. Is this code well-defined?
  2. Is it supposed to be deadlock-free?
Koosha
  • 1,492
  • 7
  • 19
  • @463035818_is_not_a_number I think OP means Coliru that the "Run this code" buttons at cppreference uses. – Ted Lyngmo Sep 24 '21 at 07:41
  • An idea to try to find the problem: Use an `osyncstream` instead of writing directly to `std::cout` and add a completion function to the `std::barrier`. Perhaps it'll show something interesting. [Prepared it here](https://godbolt.org/z/9TKbxG8TM): – Ted Lyngmo Sep 27 '21 at 21:21
  • Koosha: Did my version of your program also hang when you tried it with your local GCC 11.1.0? – Ted Lyngmo Oct 07 '21 at 21:08
  • @TedLyngmo I tried it multiple times with GCC 11.1.0. It did not generate any output (Ctrl+C after about 10 seconds of inactivity). Tried to compile it with Clang, and `syncstream` file was not found. – Koosha Oct 08 '21 at 05:28
  • @Koosha Ok, perhaps the clang++ version is too old. I get the first error with clang++ 12.0.0 on `` though, not ``. With clang++ 12.0.1, the program runs fine. – Ted Lyngmo Oct 08 '21 at 08:09

0 Answers0