Advertisement
Guest User

Example for boost shared_mutex (multiple reads/one write)

a guest
Jan 28th, 2012
1,447
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. boost::shared_mutex _access;
  2. void reader()
  3. {
  4. // get shared access
  5. boost::shared_lock lock(_access);
  6.  
  7. // now we have shared access
  8. }
  9.  
  10. void writer()
  11. {
  12. // get upgradable access
  13. boost::upgrade_lock lock(_access);
  14.  
  15. // get exclusive access
  16. boost::upgrade_to_unique_lock uniqueLock(lock);
  17. // now we have exclusive access
  18. }
  19.  
  20. boost::shared_mutex _access;
  21. void reader()
  22. {
  23. boost::shared_lock< boost::shared_mutex > lock(_access);
  24. // do work here, without anyone having exclusive access
  25. }
  26.  
  27. void conditional_writer()
  28. {
  29. boost::upgrade_lock< boost::shared_mutex > lock(_access);
  30. // do work here, without anyone having exclusive access
  31.  
  32. if (something) {
  33. boost::upgrade_to_unique_lock< boost::shared_mutex > uniqueLock(lock);
  34. // do work here, but now you have exclusive access
  35. }
  36.  
  37. // do more work here, without anyone having exclusive access
  38. }
  39.  
  40. void unconditional_writer()
  41. {
  42. boost::unique_lock< boost::shared_mutex > lock(lock);
  43. // do work here, with exclusive access
  44. }
  45.  
  46. #include <boost/thread/locks.hpp>
  47.  
  48. typedef boost::shared_mutex Lock;
  49. typedef boost::unique_lock< boost::shared_mutex > WrtieLock;
  50. typedef boost::shared_lock< boost::shared_mutex > ReadLock;
  51.  
  52. Lock myLock;
  53.  
  54.  
  55. void ReadFunction()
  56. {
  57. ReadLock r_lock(myLock);
  58. //Do reader stuff
  59. }
  60.  
  61. void WriteFunction()
  62. {
  63. WriteLock w_lock(myLock);
  64. //Do writer stuff
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement