to I don't know how a boolean member variable would help. The answer is mutexes and locks, you create a member variable mutex. Here's some code, take out the lock and see what happens. I have a simple cout here, but imagine you are doing some complex data operations within the object. #include #include class ThreadSafeClass { public: ThreadSafeClass(int id): mThreadId(id){}; void operator()() { // This function will be altering the state, so grab the lock here boost::lock_guard lock(mMutex); std::cout << "Try this with and without the lock" << i<< std::endl; } // Leave the function, pass out of scope and release the lock, private: boost::mutex mMutex; int mThreadId; }; int main() { std::vector vectorThreads; std::vector::iterator it; for (int i = 0; i < 10; ++i) { ThreadSafeClass tsEx(i); boost::thread exThread(tsEx); // This launches the threads. vectorThreads.push_back(exThread); } for (it =vectorThreads.begin(); it!=vectorThreads.end(); ++it) { (*it)->join(); } return 0; }
【在 c**z 的大作中提到】 : 如果在里面放一个 member variable, set it to true when the thread starts to : execute, and flip it when the thread returns. : 请问这样可以吗
yes if the set and flip operation is atomic. but that is no difference from using a spin lock - which is implemented with atomic operation inside
r*a
6 楼
还真不知道是不是经常堵,刚搬进来没多久 看看这里有谁家里装了吧,是那种gutter上面盖一层网子的
【在 l*****o 的大作中提到】 : 如果还是经常堵的话肯定就不好吧。。。
c*z
7 楼
I copy and paste the code into and got the following error message. Does anyone know what's going on? 1> c:\users\lyn\downloads\boost_1_51_0\boost_1_51_0\boost\thread\ win32\mutex.hpp(26) : see declaration of 'boost::mutex::mutex' 1> c:\users\lyn\downloads\boost_1_51_0\boost_1_51_0\boost\thread\ win32\mutex.hpp(22) : see declaration of 'boost::mutex' 1> This diagnostic occurred in the compiler generated function ' ThreadSafeClass::ThreadSafeClass(ThreadSafeClass &)'