Skip to content

Instantly share code, notes, and snippets.

@nglee
Last active April 3, 2020 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nglee/a6eb842a92f1b44ca3d3880b255aac80 to your computer and use it in GitHub Desktop.
Save nglee/a6eb842a92f1b44ca3d3880b255aac80 to your computer and use it in GitHub Desktop.
Automatic unlocking of interprocess_mutex with scoped_lock
#include <boost/interprocess/managed_xsi_shared_memory.hpp>
#include <boost/interprocess/xsi_key.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <iostream>
using namespace boost::interprocess;
void first_process(managed_xsi_shared_memory *shm);
void second_process(managed_xsi_shared_memory *shm);
int main()
{
managed_xsi_shared_memory *shm = nullptr;
try {
shm = new managed_xsi_shared_memory{ create_only, xsi_key("bitest4.cpp", 239), 1024 };
first_process(shm);
} catch (interprocess_exception& e) {
shm = new managed_xsi_shared_memory{ open_only, xsi_key("bitest4.cpp", 239) };
second_process(shm);
}
}
void first_process(managed_xsi_shared_memory *shm)
{
std::cout << "This is the first process." << std::endl;
interprocess_mutex *mtx = shm->find_or_construct<interprocess_mutex>("gMutex")();
scoped_lock<interprocess_mutex> lock(*mtx);
std::cout << "The first process locked an interprocess_mutex" << std::endl;
std::cout << "and is going to exit without unlocking the mutex" << std::endl;
}
void second_process(managed_xsi_shared_memory *shm)
{
std::cout << "This is the second process." << std::endl;
interprocess_mutex *mtx = shm->find_or_construct<interprocess_mutex>("gMutex")();
std::cout << "The second process is going to lock an interprocess mutex," << std::endl;
std::cout << "and if it succeeds, then a message will be shown." << std::endl;
std::cout << "If it failes, it will run indefinitely." << std::endl;
scoped_lock<interprocess_mutex> lock(*mtx);
std::cout << "The second process locked the mutex!" << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment