mutex.cpp 978 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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/mutex.hpp>
  7. #include <boost/thread/thread.hpp>
  8. #include <iostream>
  9. boost::mutex io_mutex; // The iostreams are not guaranteed to be thread-safe!
  10. class counter
  11. {
  12. public:
  13. counter() : count(0) { }
  14. int increment() {
  15. boost::unique_lock<boost::mutex> scoped_lock(mutex);
  16. return ++count;
  17. }
  18. private:
  19. boost::mutex mutex;
  20. int count;
  21. };
  22. counter c;
  23. void change_count()
  24. {
  25. int i = c.increment();
  26. boost::unique_lock<boost::mutex> scoped_lock(io_mutex);
  27. std::cout << "count == " << i << std::endl;
  28. }
  29. int main(int, char*[])
  30. {
  31. const int num_threads = 4;
  32. boost::thread_group thrds;
  33. for (int i=0; i < num_threads; ++i)
  34. thrds.create_thread(&change_count);
  35. thrds.join_all();
  36. return 0;
  37. }