recursive_mutex.cpp 1004 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright (C) 2001-2003
  2. // William E. Kempf
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. #include <boost/thread/recursive_mutex.hpp>
  7. #include <boost/thread/thread.hpp>
  8. #include <iostream>
  9. class counter
  10. {
  11. public:
  12. counter() : count(0) { }
  13. int add(int val) {
  14. boost::unique_lock<boost::recursive_mutex> scoped_lock(mutex);
  15. count += val;
  16. return count;
  17. }
  18. int increment() {
  19. boost::unique_lock<boost::recursive_mutex> scoped_lock(mutex);
  20. return add(1);
  21. }
  22. private:
  23. boost::recursive_mutex mutex;
  24. int count;
  25. };
  26. counter c;
  27. void change_count()
  28. {
  29. //std::cout << "count == " << c.increment() << std::endl;
  30. }
  31. int main(int, char*[])
  32. {
  33. const int num_threads=4;
  34. boost::thread_group threads;
  35. for (int i=0; i < num_threads; ++i)
  36. threads.create_thread(&change_count);
  37. threads.join_all();
  38. return 0;
  39. }