native_handle函数, mutex互斥锁,递归锁

1, thread类提供了native_handle()成员函数,用于获得与操作系统相关的原生线程句柄,操作系统原生的线程库就可以用原生线程句柄操作线程

#include <iostream>
#include <thread>
#include <pthread.h>        // Linux的pthread线程库头文件。
using namespace std;

void func()    // 线程任务函数。
{
    for (int ii=1;ii<=10;ii++)
    {
        cout << "ii=" << ii << endl;
        this_thread::sleep_for(chrono::seconds(1));    // 休眠1秒。
    }
}

int main()
{
    thread tt(func);          // 创建线程。

    this_thread::sleep_for(chrono::seconds(5));    // 休眠5秒。

    pthread_t thid= tt.native_handle();  // 获取Linux操作系统原生的线程句柄。

    pthread_cancel(thid);  // 取消线程。

    tt.join();   // 等待线程退出。
}

2, mutex互斥锁

#include <iostream>
#include <thread>                // 线程类头文件。
#include <mutex>                // 互斥锁类的头文件。
using namespace std;

mutex mtx;        // 创建互斥锁,保护共享资源cout对象。

// 普通函数。
void func(int bh, const string& str) {
    for (int ii = 1; ii <= 10; ii++)
    {
        mtx.lock();      // 申请加锁。
        cout << "第" << ii << "次表白:亲爱的" << bh << "号," << str << endl;
        mtx.unlock();  // 解锁。
        this_thread::sleep_for(chrono::seconds(1));     // 休眠1秒。
    }
}

int main()
{
    // 用普通函数创建线程。
    thread t1(func, 1, "我是一只傻傻鸟。");
    thread t2(func, 2, "我是一只傻傻鸟。");
    thread t3(func, 3, "我是一只傻傻鸟。");
    thread t4(func, 4, "我是一只傻傻鸟。");
    thread t5(func, 5, "我是一只傻傻鸟。");

    t1.join();         // 回收线程t1的资源。
    t2.join();         // 回收线程t2的资源。
    t3.join();         // 回收线程t3的资源。
    t4.join();         // 回收线程t4的资源。
    t5.join();         // 回收线程t5的资源。
}

3, recursive_mutex类

#include <iostream>
#include <mutex>        // 互斥锁类的头文件。
using namespace std;

class AA
{
    // 递归互斥锁允许同一线程多次获得互斥锁,可以解决同一线程多次加锁造成的死锁问题
    recursive_mutex m_mutex;
public:
    void func1() {
        m_mutex.lock();
        cout << "调用了func1()\n";
        m_mutex.unlock();
    }

    void func2() {
        m_mutex.lock();
        cout << "调用了func2()\n";
        func1();
        m_mutex.unlock();
    }
};

int main()
{
    AA aa;
    //aa.func1();
    aa.func2();
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • std:mutex 在 C++ 中,mutex 类能用于保护共享数据从多个线程同时访问的同步原语。 mutex 提...
    kotlon阅读 1,286评论 0 0
  • 第一部分: application 应用程式 应用、应用程序application framework 应用程式框...
    谷雨2058阅读 1,927评论 0 1
  • 很实用的编程英语词库,共收录一千五百余条词汇。 第一部分: application 应用程式 应用、应用程序app...
    春天的蜜蜂阅读 1,399评论 0 22
  • 使用thread创建线程 线程资源回收 虽然同一个进程的多尔线程共享进程的栈空间,但是每个子线程在整个栈中拥有自己...
    arkliu阅读 134评论 0 0
  • 互斥 互斥算法避免多个线程同时访问共享资源。这会避免数据竞争,并提供线程间的同步支持。 mutex 类 mutex...
    NINOMAE阅读 446评论 0 0