C++多线程中的锁和条件变量使用教程

在做多线程编程时,有两个场景我们都会遇到:

  1. 多线程访问共享资源,需要用到锁;
  2. 多线程间的状态同步,这个可用的机制很多,条件变量是广泛使用的一种。

今天我用一个简单的例子来给大家介绍下锁和条件变量的使用。

代码使用C++11

示例代码

#include <iostream>
#include <mutex>
#include <thread>
#include <condition_variable>
std::mutex       g_mutex;   // 用到的全局锁
std::condition_variable g_cond;   // 用到的条件变量
int g_i    = 0;
bool g_running = true;
void ThreadFunc(int n) {       // 线程执行函数
 for (int i = 0; i < n; ++i) {
  {
   std::lock_guard<std::mutex> lock(g_mutex);   // 加锁,离开{}作用域后锁释放
   ++g_i;
   std::cout << "plus g_i by func thread " << std::this_thread::get_id() << std::endl;
  }
 }
 std::unique_lock<std::mutex> lock(g_mutex);    // 加锁
 while (g_running) {
  std::cout << "wait for exit" << std::endl;
  g_cond.wait(lock);                // wait调用后,会先释放锁,之后进入等待状态;当其它进程调用通知激活后,会再次加锁
 }
 std::cout << "func thread exit" << std::endl;
}
int main() {
 int     n = 100;
 std::thread t1(ThreadFunc, n);    // 创建t1线程(func thread),t1会执行`ThreadFunc`中的指令
 for (int i = 0; i < n; ++i) {
  {
   std::lock_guard<std::mutex> lock(g_mutex);
   ++g_i;
   std::cout << "plus g_i by main thread " << std::this_thread::get_id() << std::endl;
  }
 }
 {
  std::lock_guard<std::mutex> lock(g_mutex);
  g_running = false;
  g_cond.notify_one();   // 通知其它线程
 }
 t1.join();     // 等待线程t1结束
 std::cout << "g_i = " << g_i << std::endl;
}

程序运行后,关键输出如下:

plus g_i by main thread 139921025066816
plus g_i by main thread 139921025066816
plus g_i by func thread 139921006847744
plus g_i by func thread 139921006847744
plus g_i by func thread 139921006847744
plus g_i by func thread 139921006847744
plus g_i by func thread 139921006847744
wait for exit               // func thread等待main thread发来的退出信号
plus g_i by main thread 139921025066816
plus g_i by main thread 139921025066816
plus g_i by main thread 139921025066816
plus g_i by main thread 139921025066816
plus g_i by main thread 139921025066816
plus g_i by main thread 139921025066816
plus g_i by main thread 139921025066816
plus g_i by main thread 139921025066816
plus g_i by main thread 139921025066816
plus g_i by main thread 139921025066816
func thread exit
g_i = 200     // 锁机制保证了g_i的正确

可以看到:

std::this_thread::get_id()
g_i

加锁方法介绍

加锁相关的代码为:

{
 std::lock_guard<std::mutex> lock(g_mutex);
 ......
}

要点为:

  • 首先,这在一个局部作用域内, std::lock_guard 在构造时,会调用 g_mutex->lock() 方法;
  • 局部作用域代码结束后, std:;lock_guard 的析构函数会被调用,函数中会调用 g_mutex->unlock() 方法。

这样就实现了加锁和解锁的过程,为什么不直接调用加锁解锁方法呢?

我想,这是因为如果加锁和解锁中间的代码出现了问题,导致线程函数异常退出,那么这个锁就一直无法得到释放,其它线程处理的不好的话,就会造成死锁了。

条件变量使用介绍

  • 当线程调用 g_cond.wait(lock) 前要先手动调用 lock->lock() ,这里是通过 std::unique_lock 的构造方法实现的;
  • 当线程调用 g_cond.wait(lock) 进入等待后,会调用 lock->unlock() 方法,所以这也是前面构造lock时使用了 std::unique_lock ;
  • 通知使用的 g_cond.notify_one() ,这个可以通知一个线程,另外还有 g_cond.notify_all() 用于通知所有线程;
  • 线程收到通知的代码放在一个while循环中,这是为了防止APUE中提到的虚假通知。

结束语

以上所述是小编给大家介绍的C++多线程中的锁和条件变量使用教程,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!

(0)

相关推荐

  • C++多线程编程简单实例

    C++本身并没有提供任何多线程机制,但是在windows下,我们可以调用SDK win32 api来编写多线程的程序,下面就此简单的讲一下: 创建线程的函数 复制代码 代码如下: HANDLE CreateThread(     LPSECURITY_ATTRIBUTES lpThreadAttributes, // SD     SIZE_T dwStackSize,                       // initial stack size     LPTHREAD_START_

  • c++多线程之死锁的发生的情况解析(包含两个归纳,6个示例)

    一.死锁会在什么情况发生 1.假设有如下代码 mutex; //代表一个全局互斥对象 void A() { mutex.lock(); //这里操作共享数据 B(); //这里调用B方法 mutex.unlock(); return; } void B() { mutex.lock(); //这里操作共享数据 mutex.unlock(); return; } 此时会由于在A.B方法中相互等待unlock而导致死锁. 2.假设有如何代码 mutex; //代表一个全局互斥对象 void A()

  • C++ 关于MFC多线程编程的注意事项

    在多线程编程中,最简单的方法,无非就是利用 AfxBeginThread  来创建一个工作线程,看一下这个函数的说明: 复制代码 代码如下: CWinThread* AFXAPI AfxBeginThread( AFX_THREADPROC pfnThreadProc, LPVOID pParam, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags = 0, LPSECURITY_AT

  • C++基于消息队列的多线程实现示例代码

    前言 实现消息队列的关键因素是考量不同线程访问消息队列的同步问题.本实现涉及到几个知识点 std::lock_guard 介绍 std::lock_gurad 是 C++11 中定义的模板类.定义如下: template <class Mutex> class lock_guard; lock_guard 对象通常用于管理某个锁(Lock)对象,因此与 Mutex RAII 相关,方便线程对互斥量上锁,即在某个 lock_guard 对象的声明周期内,它所管理的锁对象会一直保持上锁状态:而 l

  • C++多线程编程时的数据保护

    在编写多线程程序时,多个线程同时访问某个共享资源,会导致同步的问题,这篇文章中我们将介绍 C++11 多线程编程中的数据保护. 数据丢失 让我们从一个简单的例子开始,请看如下代码: #include <iostream> #include <string> #include <thread> #include <vector> using std::thread; using std::vector; using std::cout; using std::

  • C++实现多线程查找文件实例

    主要是多线程的互斥 文件 的查找 多线程互斥的框架 复制代码 代码如下: //线程函数  UINT FinderEntry(LPVOID lpParam)  {      //CRapidFinder通过参数传递进来       CRapidFinder* pFinder = (CRapidFinder*)lpParam;      CDirectoryNode* pNode = NULL;      BOOL bActive = TRUE; //bActive为TRUE,表示当前线程激活   

  • C++开发:为什么多线程读写shared_ptr要加锁的详细介绍

    我在<Linux 多线程服务端编程:使用 muduo C++ 网络库>第 1.9 节"再论 shared_ptr 的线程安全"中写道: (shared_ptr)的引用计数本身是安全且无锁的,但对象的读写则不是,因为 shared_ptr 有两个数据成员,读写操作不能原子化.根据文档(http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm#ThreadSafety), shared_ptr 的线程

  • C/C++ 多线程的学习心得总结

    个人觉得在学习多线程编程之前最好先了解进程和线程的关系, 然后在学习线程工作方式的过程中动手写个(我是从抄开始的)多线程的小程序, 会对学习多线程有很大的帮助, 否则只有理论是很抽象的. 在学习多线程编程之前, 必须先知道什么是 线程函数, 线程函数就是另一个线程的入口函数. 默认情况下一个我们所写的代码都是只有一个线程的, 而这个线程的入口函数就是main() 函数, 这是系统默认的. 而我们创建的另一个线程也需要一个函数来进入, 这个函数就叫做线程函数. 在C/C++中, 可以调用 '运行期

  • C++ 中消息队列函数实例详解

    C++ 中消息队列函数实例详解 1.消息队列结构体的定义 typedef struct{ uid_t uid; /* owner`s user id */ gid_t gid; /* owner`s group id */ udi_t cuid; /* creator`s user id */ gid_t cgid; /* creator`s group id */ mode_t mode; /* read-write permissions 0400 MSG_R 0200 MSG_W*/ ul

  • linux下的C\C++多进程多线程编程实例详解

    linux下的C\C++多进程多线程编程实例详解 1.多进程编程 #include <stdlib.h> #include <sys/types.h> #include <unistd.h> int main() { pid_t child_pid; /* 创建一个子进程 */ child_pid = fork(); if(child_pid == 0) { printf("child pid\n"); exit(0); } else { print

随机推荐