浅谈c++11线程的互斥量

作者:lsgxeva 时间:2023-02-14 18:00:44 

为什么需要互斥量

在多任务操作系统中,同时运行的多个任务可能都需要使用同一种资源。这个过程有点类似于,公司部门里,我在使用着打印机打印东西的同时(还没有打印完),别人刚好也在此刻使用打印机打印东西,如果不做任何处理的话,打印出来的东西肯定是错乱的。


#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <string>
#include <chrono>
#include <thread>

// 打印机
void printer(const char *str)
{
   while(*str != '\0')
   {
       std::cout << *str;
       str++;
       std::this_thread::sleep_for(std::chrono::milliseconds(1000));
   }
   std::cout << std::endl;
}

// 线程一
void func1()
{
   const char *str = "hello";
   printer(str);
}

// 线程二
void func2()
{
   const char *str = "world";
   printer(str);
}

void mytest()
{
   std::thread t1(func1);
   std::thread t2(func2);

t1.join();
   t2.join();

return;
}

int main()
{
   mytest();

system("pause");
   return 0;
}

独占互斥量std::mutex

互斥量的基本接口很相似,一般用法是通过lock()方法来阻塞线程,直到获得互斥量的所有权为止。在线程获得互斥量并完成任务之后,就必须使用unlock()来解除对互斥量的占用,lock()和unlock()必须成对出现。try_lock()尝试锁定互斥量,如果成功则返回true, 如果失败则返回false,它是非阻塞的。


#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <string>
#include <chrono>
#include <thread>
#include <mutex>

std::mutex g_lock; //全局互斥锁对象,#include <mutex>

// 打印机
void printer(const char *str)
{
   g_lock.lock(); //上锁
   while(*str != '\0')
   {
       std::cout << *str;
       str++;
       std::this_thread::sleep_for(std::chrono::milliseconds(1000));
   }
   std::cout << std::endl;
   g_lock.unlock(); // 解锁
}

// 线程一
void func1()
{
   const char *str = "hello";
   printer(str);
}

// 线程二
void func2()
{
   const char *str = "world";
   printer(str);
}

void mytest()
{
   std::thread t1(func1);
   std::thread t2(func2);

t1.join();
   t2.join();

return;
}

int main()
{
   mytest();

system("pause");
   return 0;
}

使用std::lock_guard可以简化lock/unlock的写法,同时也更安全,因为lock_guard在构造时会自动锁定互斥量,而在退出作用域后进行析构时就会自动解锁,从而避免忘了unlock操作。


#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <string>
#include <chrono>
#include <thread>
#include <mutex>

std::mutex g_lock; //全局互斥锁对象,#include <mutex>

// 打印机
void printer(const char *str)
{
   std::lock_guard<std::mutex> locker(g_lock); // lock_guard 上锁
   while(*str != '\0')
   {
       std::cout << *str;
       str++;
       std::this_thread::sleep_for(std::chrono::milliseconds(1000));
   }
   std::cout << std::endl;
   // 即将推出作用域 lock_guard 会自动解锁
}

// 线程一
void func1()
{
   const char *str = "hello";
   printer(str);
}

// 线程二
void func2()
{
   const char *str = "world";
   printer(str);
}

void mytest()
{
   std::thread t1(func1);
   std::thread t2(func2);

t1.join();
   t2.join();

return;
}

int main()
{
   mytest();

system("pause");
   return 0;
}

原子操作

所谓的原子操作,取的就是“原子是最小的、不可分割的最小个体”的意义,它表示在多个线程访问同一个全局资源的时候,能够确保所有其他的线程都不在同一时间内访问相同的资源。也就是他确保了在同一时刻只有唯一的线程对这个资源进行访问。这有点类似互斥对象对共享资源的访问的保护,但是原子操作更加接近底层,因而效率更高。


#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <string>
#include <chrono>
#include <thread>

//全局的结果数据
long total = 0;

//点击函数
void func()
{
   for(int i = 0;  i < 1000000; ++i)
   {
       // 对全局数据进行无锁访问
       total += 1;
   }
}

void mytest()
{
   clock_t start = clock();    // 计时开始

//线程
   std::thread t1(func);
   std::thread t2(func);

t1.join();
   t2.join();

clock_t end = clock();    // 计时结束

std::cout << "total = " << total << std::endl;
   std::cout << "time = " << end-start << " ms" << std::endl;

return;
}

int main()
{
   mytest();

system("pause");
   return 0;
}

由于线程间对数据的竞争而导致每次运行的结果都不一样。因此,为了防止数据竞争问题,我们需要对total进行原子操作。

浅谈c++11线程的互斥量

浅谈c++11线程的互斥量

浅谈c++11线程的互斥量

通过互斥锁进行原子操作:


#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <string>
#include <chrono>
#include <thread>
#include <mutex>

std::mutex g_lock;

//全局的结果数据
long total = 0;

//点击函数
void func()
{
   for(int i = 0;  i < 1000000; ++i)
   {
       g_lock.lock(); // 加锁
       total += 1;
       g_lock.unlock(); // 加锁
   }
}

void mytest()
{
   clock_t start = clock();    // 计时开始

//线程
   std::thread t1(func);
   std::thread t2(func);

t1.join();
   t2.join();

clock_t end = clock();    // 计时结束

std::cout << "total = " << total << std::endl;
   std::cout << "time = " << end-start << " ms" << std::endl;

return;
}

int main()
{
   mytest();

system("pause");
   return 0;
}

每次运行的结果都一样,只是耗时长点。

浅谈c++11线程的互斥量

浅谈c++11线程的互斥量

在新标准C++11,引入了原子操作的概念。

如果我们在多个线程中对这些类型的共享资源进行操作,编译器将保证这些操作都是原子性的,也就是说,确保任意时刻只有一个线程对这个资源进行访问,编译器将保证多个线程访问这个共享资源的正确性。从而避免了锁的使用,提高了效率。


#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <string>
#include <chrono>
#include <thread>
#include <atomic>

//原子数据类型
std::atomic<long> total(0); //需要头文件 #include <atomic>

//点击函数
void func()
{
   for(int i = 0;  i < 1000000; ++i)
   {
       //
       total += 1;
   }
}

void mytest()
{
   clock_t start = clock();    // 计时开始

//线程
   std::thread t1(func);
   std::thread t2(func);

t1.join();
   t2.join();

clock_t end = clock();    // 计时结束

std::cout << "total = " << total << std::endl;
   std::cout << "time = " << end-start << " ms" << std::endl;

return;
}

int main()
{
   mytest();

system("pause");
   return 0;
}

原子操作的实现跟普通数据类型类似,但是它能够在保证结果正确的前提下,提供比mutex等锁机制更好的性能。

来源:https://www.cnblogs.com/lsgxeva/p/7789081.html

标签:c++,线程,互斥量
0
投稿

猜你喜欢

  • Java监听器的作用及用法代码示例

    2023-06-24 06:59:07
  • 浅谈Springboot下引入mybatis遇到的坑点

    2023-09-09 05:55:09
  • Java 详解包装类Integer与int有哪些共通和不同

    2022-06-15 20:12:18
  • Spring Security前后分离校验token的实现方法

    2023-06-26 17:00:30
  • Spring Boot项目维护全局json数据代码实例

    2023-04-17 23:24:10
  • SpringBoot FreeWorker模板技术解析

    2023-08-09 09:14:39
  • Android 图片处理避免出现oom的方法详解

    2023-09-07 07:26:12
  • 基于java构造方法Vector创建对象源码分析

    2023-11-25 11:27:54
  • c#扩展datatable转json示例

    2022-08-19 10:44:55
  • Springboot项目打war包docker包找不到resource下静态资源的解决方案

    2022-01-01 07:03:55
  • Input系统之InputReader处理按键事件详解

    2023-11-09 20:57:05
  • java实现将结果集封装到List中的方法

    2021-10-27 22:29:45
  • 如何将默认的maven仓库改为阿里的maven仓库

    2022-09-30 14:16:31
  • spring boot中配置hikari连接池属性方式

    2022-11-13 06:06:44
  • 用C#实现启动另一程序的方法实例

    2023-06-20 12:05:43
  • Javaweb mybatis接口开发实现过程详解

    2022-03-11 22:02:21
  • C#中单问号(?)和双问号(??)的用法整理

    2021-08-27 02:50:53
  • 详解如何更改SpringBoot TomCat运行方式

    2021-11-17 02:48:01
  • C#非矩形窗体实现方法

    2023-04-09 15:11:39
  • C#设计模式之工厂模式

    2023-07-10 13:43:33
  • asp之家 软件编程 m.aspxhome.com