您的位置:首页 > 编程语言 > C语言/C++

c++ 11 多线程编程--互斥体类(1)

2016-08-29 17:30 471 查看
C++11支持的互斥的形式包括互斥体和锁
(一)互斥体类
  ->非定时互斥体类
  std::mutex
  std::recursive_mutex
  ->定时互斥体类
  std::timed_mutex
  std::recursive_timed_mutex

 (1)std::mutex
     C++11 最基本的互斥量,std::mutex对象提供了独占所有权的特性->不支持递归的对std::mutex 对象上锁
     ->构造函数
     std::mutex 不允许拷贝构造,也不允许move拷贝,最初产生的对象是unlocked状态的
     ->lock()
     调用线程将锁住该互斥量,会出现一下三种情况:
如果改互斥量当前没有被锁住,则调用线程将该互斥量锁住,直到unlocked之前,该线程一直拥有该锁。
如果当前互斥量被其他线程锁住,则当前调用线程被阻塞住,直到该互斥量被当前线程释放。
如果当前互斥量被当前线程锁住,则会产生死锁。 

//mutex类.cpp : 定义控制台应用程序的入口点。
//
//mutex::lock example
#include "stdafx.h"
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex

volatile int counter(0); // non-atomic counter
std::mutex mtx;           // locks access to counter

void attempt_10k_increases()
{
for (int i = 0; i<10000; ++i)
{
mtx.lock();  // 如果counter 被锁住某一线程锁住,则其它线程会被阻塞直到 counter被释放 但能保证每个线程都调用一次 ++counter
++counter;
mtx.unlock();
}
}

int main()
{
std::thread threads[10];
// spawn 10 threads:
for (int i = 0; i<10; ++i)
threads[i] = std::thread(attempt_10k_increases);

for (auto& th : threads) th.join();
std::cout << counter << " successful increases of the counter.\n";

return 0;
}
/*输出结果*/
//10000

->try_lock()
      尝试锁住互斥量,如果互斥量被其他线程占有,当前线程也不会被阻塞。线程调用该函数会出现一下三种情况:
如果改互斥量当前没有被锁住,则调用线程将该互斥量锁住,直到unlocked之前,该线程一直拥有该锁。
如果当前互斥量被其他线程锁住,则当前调用线程返回false,且不会被阻塞住。
如果当前互斥量被当前线程锁住,则会产生死锁。  
// mutex类.cpp : 定义控制台应用程序的入口点。
//
// mutex::try_lock example
#include "stdafx.h"
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex

volatile int counter(0); // non-atomic counter
std::mutex mtx;           // locks access to counter
void attempt_10k_increases()
{
for (int i = 0; i<10000; ++i)
{
if (mtx.try_lock())//如果counter被其他线程锁住,mtx.try_lock为false counter 没有进行++ 运算,导致counter的值不确定
{   // only increase if currently not locked:
++counter;
mtx.unlock();
}
}
}

int main()
{
std::thread threads[10];
// spawn 10 threads:
for (int i = 0; i<10; ++i)
threads[i] = std::thread(attempt_10k_increases);
for (auto& th : threads) th.join();
std::cout << counter << " successful increases of the counter.\n";
return 0;
}
/*输出结果*/
//1~~100000之间的任何数值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 多线程