counter.cpp 655 B

12345678910111213141516171819202122232425262728
  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 mutex;
  10. int counter=0;
  11. void change_count()
  12. {
  13. boost::mutex::scoped_lock lock(mutex);
  14. int i = ++counter;
  15. std::cout << "count == " << i << std::endl;
  16. }
  17. int main()
  18. {
  19. const int num_threads = 4;
  20. boost::thread_group thrds;
  21. for (int i=0; i < num_threads; ++i)
  22. thrds.create_thread(&change_count);
  23. thrds.join_all();
  24. }