You have three separate objects, and none of them can see the other mutex_, because this element is created inside each object.
Perhaps you also wanted to make mutex_ static?
Edit: if I make the mutex statics and remove the statics from the i variable, then it works, as I assume you meant it. It seems that something like this is happening: each thread immediately enters the loop and is not blocked from each other due to the fact that the mutex is not static. By the time they are all output to the console (I donβt remember if there is a mutual exception when writing to cout), and I get incremented, they all see the static me as 30 and exit.
Edit 2: No, itβs still not correct, since some runs still have interspersed values.
Edit 3: the reason it compiles is because your scoped_lock is temporary, which seems to throw the compiler out of the fact that mutex_ should be static. Instead, try using the following code:
#include <iostream> #include "boost\thread\mutex.hpp" #include "boost\thread\thread.hpp" class ThreadWorker { public: ThreadWorker() {} virtual ~ThreadWorker() {} static void FirstCount(int threadId) { // Created object f here rather than temprary boost::mutex::scoped_lock f(mutex_); int i = 0; // Not static for(i = 1; i <= 30; i++) { std::cout << i << ": Hi from thread: " << threadId << std::endl; } } private: static boost::mutex mutex_; // Static }; // Storage for static boost::mutex ThreadWorker::mutex_; int main(int argc, char* argv[]) { boost::thread thread1(&ThreadWorker::FirstCount, 1); boost::thread thread2(&ThreadWorker::FirstCount, 2); boost::thread thread3(&ThreadWorker::FirstCount, 3); thread1.join(); thread2.join(); thread3.join(); std::string input; std::cout << "Press <enter> to finish...\n"; std::getline( std::cin, input ); return 0; }
source share