Imported Upstream version 1.57.0
[platform/upstream/boost.git] / boost / interprocess / sync / detail / common_algorithms.hpp
1 //////////////////////////////////////////////////////////////////////////////
2 //
3 // (C) Copyright Ion Gaztanaga 2012-2013. Distributed under the Boost
4 // Software License, Version 1.0. (See accompanying file
5 // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 //
7 // See http://www.boost.org/libs/interprocess for documentation.
8 //
9 //////////////////////////////////////////////////////////////////////////////
10
11 #ifndef BOOST_INTERPROCESS_SYNC_DETAIL_COMMON_ALGORITHMS_HPP
12 #define BOOST_INTERPROCESS_SYNC_DETAIL_COMMON_ALGORITHMS_HPP
13
14 #if defined(_MSC_VER)
15 #  pragma once
16 #endif
17
18 #include <boost/interprocess/detail/config_begin.hpp>
19 #include <boost/interprocess/detail/workaround.hpp>
20
21 #include <boost/interprocess/sync/spin/wait.hpp>
22
23 namespace boost {
24 namespace interprocess {
25 namespace ipcdetail {
26
27 template<class MutexType>
28 bool try_based_timed_lock(MutexType &m, const boost::posix_time::ptime &abs_time)
29 {
30    //Same as lock()
31    if(abs_time == boost::posix_time::pos_infin){
32       m.lock();
33       return true;
34    }
35    //Always try to lock to achieve POSIX guarantees:
36    // "Under no circumstance shall the function fail with a timeout if the mutex
37    //  can be locked immediately. The validity of the abs_timeout parameter need not
38    //  be checked if the mutex can be locked immediately."
39    else if(m.try_lock()){
40       return true;
41    }
42    else{
43       spin_wait swait;
44       while(microsec_clock::universal_time() < abs_time){
45          if(m.try_lock()){
46             return true;
47          }
48          swait.yield();
49       }
50       return false;
51    }
52 }
53
54 template<class MutexType>
55 void try_based_lock(MutexType &m)
56 {
57    if(!m.try_lock()){
58       spin_wait swait;
59       do{
60          if(m.try_lock()){
61             break;
62          }
63          else{
64             swait.yield();
65          }
66       }
67       while(1);
68    }
69 }
70
71 }  //namespace ipcdetail
72 }  //namespace interprocess
73 }  //namespace boost
74
75 #include <boost/interprocess/detail/config_end.hpp>
76
77 #endif   //BOOST_INTERPROCESS_SYNC_DETAIL_COMMON_ALGORITHMS_HPP