服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - 浅谈c++11线程的互斥量

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

2021-11-14 13:57lsgxeva C/C++

互斥量是个类对象,理解成一把锁(保护共享数据,其他想操作共享数据的线程必须等待解锁),互斥量使用要小心,保护数据不多也不少,少了则没达到保护效果,多了则影响效率。本文将介绍c++11线程的互斥量,感兴趣的同学,

为什么需要互斥量

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#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,它是非阻塞的。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#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操作。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#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;
}

原子操作

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#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线程的互斥量

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#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,引入了原子操作的概念。

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#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等锁机制更好的性能。

以上就是浅谈c++11线程的互斥量的详细内容,更多关于c++11线程的互斥量的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/lsgxeva/p/7789081.html

延伸 · 阅读

精彩推荐
  • C/C++OpenCV实现拼接图像的简单方法

    OpenCV实现拼接图像的简单方法

    这篇文章主要为大家详细介绍了OpenCV实现拼接图像的简单方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    iteye_183805102021-07-29
  • C/C++c/c++实现获取域名的IP地址

    c/c++实现获取域名的IP地址

    本文给大家汇总介绍了使用c/c++实现获取域名的IP地址的几种方法以及这些方法的核心函数gethostbyname的详细用法,非常的实用,有需要的小伙伴可以参考下...

    C++教程网10262021-03-16
  • C/C++C语言main函数的三种形式实例详解

    C语言main函数的三种形式实例详解

    这篇文章主要介绍了 C语言main函数的三种形式实例详解的相关资料,需要的朋友可以参考下...

    ieearth6912021-05-16
  • C/C++深入C++拷贝构造函数的总结详解

    深入C++拷贝构造函数的总结详解

    本篇文章是对C++中拷贝构造函数进行了总结与介绍。需要的朋友参考下...

    C++教程网5182020-11-30
  • C/C++C语言实现双人五子棋游戏

    C语言实现双人五子棋游戏

    这篇文章主要为大家详细介绍了C语言实现双人五子棋游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    两片空白7312021-11-12
  • C/C++使用C++制作简单的web服务器(续)

    使用C++制作简单的web服务器(续)

    本文承接上文《使用C++制作简单的web服务器》,把web服务器做的功能稍微强大些,主要增加的功能是从文件中读取网页并返回给客户端,而不是把网页代码...

    C++教程网5492021-02-22
  • C/C++c/c++内存分配大小实例讲解

    c/c++内存分配大小实例讲解

    在本篇文章里小编给大家整理了一篇关于c/c++内存分配大小实例讲解内容,有需要的朋友们可以跟着学习参考下。...

    jihite5172022-02-22
  • C/C++关于C语言中E-R图的详解

    关于C语言中E-R图的详解

    今天小编就为大家分享一篇关于关于C语言中E-R图的详解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看...

    Struggler095962021-07-12