I have this simple program:
// shared_memory.hpp
#include <atomic>
#include <cstdint>
struct SharedMemory {
std::atomic<std::uint64_t> last_update_nanotime;
};
// sender.cpp
#include <iostream>
#include <thread>
#include <boost/interprocess/managed_mapped_file.hpp>
#include "shared_memory.hpp"
int main() {
std::string filename = "/tmp/boost_shared_memory";
boost::interprocess::managed_mapped_file mfile(
boost::interprocess::open_or_create, filename.c_str(), 1000);
auto* shared_mem = mfile.find_or_construct<SharedMemory>("SharedMemory")();
while(true) {
std::cout << "Locking & writing" << std::endl;
{
uint64_t nanotime = std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now().time_since_epoch()).count();
shared_mem->last_update_nanotime = nanotime;
}
std::cout << "Set time " << shared_mem->last_update_nanotime << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
// receiver.cpp
#include <iostream>
#include <boost/interprocess/managed_mapped_file.hpp>
#include <thread>
#include "shared_memory.hpp"
int main() {
std::string filename = "/tmp/boost_shared_memory";
boost::interprocess::managed_mapped_file mfile(
boost::interprocess::open_or_create, filename.c_str(), 1000);
auto* shared_mem = mfile.find_or_construct<SharedMemory>("SharedMemory")();
uint64_t last_update_nanotime = shared_mem->last_update_nanotime;
while(true) {
std::cout << "Waiting" << std::endl;
{
shared_mem->last_update_nanotime.wait(last_update_nanotime);
last_update_nanotime = shared_mem->last_update_nanotime;
std::cout << "Received: " << shared_mem->message << std::endl;
}
}
}
Why does receiver.cpp hang at shared_mem->last_update_nanotime.wait(last_update_nanotime)
?
Doing a busy-wait on the value of shared_mem->last_update_nanotime instead of using wait() works fine.
I’m using g++ 13.1.0 and -std=gnu++23
although this should be supported in C++20 as well.