c**z 发帖数: 669 | 1 如果在里面放一个 member variable, set it to true when the thread starts to
execute, and flip it when the thread returns.
请问这样可以吗 | s***0 发帖数: 117 | 2
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. : 请问这样可以吗
| x****5 发帖数: 293 | 3 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 | c**z 发帖数: 669 | 4 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 &)' |
|