0

I am studying about futex synchronisation Following up the manual , I tried to syncroniaze threads using boost futex However the threads never wake up

#include <iostream>
#include <atomic>
#include <boost/fiber/detail/futex.hpp>
#include <thread>
#include <vector>
#include <chrono>
void wait(std::atomic<int>  & futexp)
{
    int one = 1;
    while(std::atomic_compare_exchange_strong(&futexp, &one, 0))
    {}
    std::cout << std::this_thread::get_id() << "," << futexp.load() << std::endl;
    boost::fibers::detail::futex_wait(&futexp,0);
   // std::this_thread::sleep_for(std::chrono::milliseconds(5000));

}
void fpost(std::atomic<int>  & futexp)
{
    int zero = 0;
    if (std::atomic_compare_exchange_strong(&futexp, &zero, 1)) {
     boost::fibers::detail::futex_wake(&futexp);
    }
}

std::atomic<int>  futexp{1};
int main() {
    std::vector<std::thread>  vec;
    for(int i =0 ; i< 5;++i)
    {
        vec.emplace_back([]()
        {
            wait(futexp);
            fpost(futexp);
        });
    }
    for(auto & el : vec)
    {
        el.join();
    }  
}

Code demo

I am using boost 1.66 and gcc 9.1 What goes wrong with this piece of code ?

getsoubl
  • 808
  • 10
  • 25

1 Answers1

1

You can't use Boost.Fiber synchronisation primitives for threads, they're only for fibers. And a general rule for Boost is to avoid using any type in a detail namespace; these are implementation details not intended for direct use and should be considered private. I suggest reading the docs if you're curious.

Almost all implementations of the regular std::mutex on Linux now use a futex under the hood anyway.

Miral
  • 12,637
  • 4
  • 53
  • 93