I'm attempting to use the timed_wait
function in boost::interprocess::interprocess_semaphore
.
bool timed_wait(const boost::posix_time::ptime & abs_time)
In all of the Boost documentation and Stack Overflow questions that I've researched, there doesn't appear to be a single straightforward example on how to use timed_wait for a simple duration like 5 seconds. I can't figure out how to initialize a boost::posix_time::ptime object that specifies a time duration.
The closest I've gotten is the following, which appears to immediately timeout instead of timeout after 5 seconds:
while (true)
{
boost::posix_time::ptime wait_time(boost::interprocess::microsec_clock::local_time());
wait_time = wait_time + boost::posix_time::microseconds(5000000);
printf("thread 1 wait\n");
bool result = binary_sem.timed_wait(wait_time);
if (result == true)
{
printf("thread 1 acquire\n");
}
else
{
printf("timeout\n");
}
}
Help would be greatly appreciated!
Looks like the base should be UTC:
#include <boost/interprocess/sync/interprocess_semaphore.hpp>
#include <iostream>
namespace pt = boost::posix_time;
int main() {
using clock = boost::interprocess::microsec_clock;
boost::interprocess::interprocess_semaphore sem(3);
auto deadline = clock::universal_time() + pt::seconds(5);
for (auto i : {1,2,3,4})
std::cout << "#" << i << " acquired? " << sem.timed_wait(deadline) << "\n";
}
Prints
#1 acquired? 1
#2 acquired? 1
#3 acquired? 1
#4 acquired? 0
real 0m5,005s
user 0m0,001s
sys 0m0,004s