转自:http://www.bogotobogo.com/cplusplus/C11/6_C11_Thread_with_Move_Semantics.php
Thread with Move Semantics
#include
#include
#include
#include
#include
using namespace std;
void task(int i) {
cout << "workers " << i << endl;
}
int main() {
vector workers;
for (int i = 0; i < 5; i++)
{
/* auto t = thread([i]() {
cout << "thread function" <
Sharing resources
//http://www.bogotobogo.com/cplusplus/C11/7_C11_Thread_Sharing_Memory.php
#include
#include
#include
#include
using namespace std;
/*
This seemingly innocent short code has already an issue of
race condition for a resource, cout.:
*/
mutex mu;
void share_function(string s,int id) {
mu.lock();
cout << s<< " "<
Mutexes
lock()、unlock()、lock_guard()
In C++, we create a mutex by constructing an instance of std::mutex, lock it with a call to the member function lock(), and unlock it with a call to the member function unlock(). However, it is not a good practice to call the member functions directly, because this means that we have to remember to call unlock() on every code path out of a function, including those due to exceptions.
In other words, if we have an exception in the code after the lock() but before the unlock(), then we'll have a problem. The resources are in locked state!
So, the Standard C++ Library provides the std::lock_guard class template, which implements that RAII idiom for a mutex. It locks the supplied mutex on construction and unlocks it on destruction, thus ensuring a locked mutex is always correctly unlocked.
The example below shows how to protect a list that can be accessed by multiple threads using a std::mutex, along with std::lock_guard. Both of these are declared in the
std::lock_guard 与mutex配合使用,把锁放到lock_guard中时,mutex自动上锁,lock_guard析构时,同时把mutex解锁。
#include
#include
#include
#include
#include
using namespace std;
list MyList;
mutex myMutex;
const int MAX = 100;
void addToList(int interval,int id) {
//对这个函数的访问是互斥的
lock_guard guard(myMutex);
for (int i = 0; i < MAX; i++){
if (i%interval == 0)
MyList.push_back(i);
}
cout << "thread " << id << "runing..........." << endl;
}
void PrintList() {
//对这个函数的访问是互斥的
lock_guard guard(myMutex);
for (auto it = MyList.begin(); it != MyList.end(); it++) {
cout << *it << ","<