When multiple threads access the same resource, the simplest way to ensure data consistency is to use mutexes (mutexes).
(1). Directly manipulate the mutex, that is, the Lock/unlock function that invokes the mutex directly. This example incidentally uses Boost::thread_group to create a set of threads.
[CPP] View plain copy
#include <iostream>
#include <boost/thread/mutex.hpp>
#include < Boost/thread/thread.hpp>
Boost::mutex mutex;
int count = 0;
void Counter () {
Mutex.lock ();
int i = ++count;
Std::cout << "Count = =" www.furggw.com/<< i << Std::endl;
//If there is an exception to the preceding code, the unlock will not be transferred.
Mutex.unlock ();
}
int main () {
//creates a set of threads.
Boost::thread_group Threads;
for (int i = 0; I www.mcyulegw.com< 4; ++i) {
Threads.create_thread (&counter);
}
//waits for all threads to end.
Threads.join_all ();
return 0;
}
(2). Use Lock_guard to automatically locking, unlock. The principle is RAII, and the smart pointer is similar to
[CPP] View plain copy
#include <iostream>
#include <boost/thread/lock_guard.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
Boost::mutex mutex;
int count = 0;
void Counter () {
///Lock_guard locks in the constructor and unlocks in the destructor.
Boost::lock_guard<boost::mutex> Lock (mutex);
int i = ++count;
Std::cout << "Count = =" << i << Std::endl;
}
int main () {
Boost::thread_group threads;
for (int i = 0; i < 4; ++i) {
Threads.create_thread (&counter);
}
Threads.join_all ();
return 0;
}
(3). Use Unique_lock to automatically locking, unlock. The
Unique_lock is the same as the lock_guard principle, but it provides more functionality (such as the ability to combine conditional variables). Note: Mutex::scoped_lock is actually a typedef of unique_lock<mutex>.
[CPP] View plain copy
#include <iostream>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
Boost::mutex Mutex;
int count = 0;
void Counter () {
Boost::unique_lock<boost::mutex> lock (mutex);
int i = ++count;
Std::cout << "Count = =" << i << Std::endl;
}
int main () {
Boost::thread_group threads;
for (int i = 0; i < 4; ++i) {
Threads.create_thread (&counter);
}
Threads.join_all ();
return 0;
C++11mutex (Mutual exclusion Lock) detailed