fix doc example typo
[boost.git] / boost / thread / win32 / basic_recursive_mutex.hpp
blob05eb8d7630b3d99993af4b2bea6233cd360b7f0c
1 #ifndef BOOST_BASIC_RECURSIVE_MUTEX_WIN32_HPP
2 #define BOOST_BASIC_RECURSIVE_MUTEX_WIN32_HPP
4 // basic_recursive_mutex.hpp
5 //
6 // (C) Copyright 2006-8 Anthony Williams
7 //
8 // Distributed under the Boost Software License, Version 1.0. (See
9 // accompanying file LICENSE_1_0.txt or copy at
10 // http://www.boost.org/LICENSE_1_0.txt)
12 #include "thread_primitives.hpp"
13 #include "basic_timed_mutex.hpp"
15 #include <boost/config/abi_prefix.hpp>
17 namespace boost
19 namespace detail
21 template<typename underlying_mutex_type>
22 struct basic_recursive_mutex_impl
24 long recursion_count;
25 long locking_thread_id;
26 underlying_mutex_type mutex;
28 void initialize()
30 recursion_count=0;
31 locking_thread_id=0;
32 mutex.initialize();
35 void destroy()
37 mutex.destroy();
40 bool try_lock()
42 long const current_thread_id=win32::GetCurrentThreadId();
43 return try_recursive_lock(current_thread_id) || try_basic_lock(current_thread_id);
46 void lock()
48 long const current_thread_id=win32::GetCurrentThreadId();
49 if(!try_recursive_lock(current_thread_id))
51 mutex.lock();
52 BOOST_INTERLOCKED_EXCHANGE(&locking_thread_id,current_thread_id);
53 recursion_count=1;
56 bool timed_lock(::boost::system_time const& target)
58 long const current_thread_id=win32::GetCurrentThreadId();
59 return try_recursive_lock(current_thread_id) || try_timed_lock(current_thread_id,target);
61 template<typename Duration>
62 bool timed_lock(Duration const& timeout)
64 return timed_lock(get_system_time()+timeout);
67 void unlock()
69 if(!--recursion_count)
71 BOOST_INTERLOCKED_EXCHANGE(&locking_thread_id,0);
72 mutex.unlock();
76 private:
77 bool try_recursive_lock(long current_thread_id)
79 if(::boost::detail::interlocked_read_acquire(&locking_thread_id)==current_thread_id)
81 ++recursion_count;
82 return true;
84 return false;
87 bool try_basic_lock(long current_thread_id)
89 if(mutex.try_lock())
91 BOOST_INTERLOCKED_EXCHANGE(&locking_thread_id,current_thread_id);
92 recursion_count=1;
93 return true;
95 return false;
98 bool try_timed_lock(long current_thread_id,::boost::system_time const& target)
100 if(mutex.timed_lock(target))
102 BOOST_INTERLOCKED_EXCHANGE(&locking_thread_id,current_thread_id);
103 recursion_count=1;
104 return true;
106 return false;
111 typedef basic_recursive_mutex_impl<basic_timed_mutex> basic_recursive_mutex;
112 typedef basic_recursive_mutex_impl<basic_timed_mutex> basic_recursive_timed_mutex;
116 #define BOOST_BASIC_RECURSIVE_MUTEX_INITIALIZER {0}
118 #include <boost/config/abi_suffix.hpp>
120 #endif