并发链表

这篇博客介绍了如何在C++中实现并发安全的有序链表,利用lock coupling方法处理并发操作。文章通过示例代码展示了如何进行插入和删除操作,并强调每次操作前必须锁定head头指针以确保并发安全。同时,文中提醒在插入时要注意判断key的唯一性。
摘要由CSDN通过智能技术生成

实现支持并发安全的有序链表。

C++并发

头文件

  • <atomic>
    • 该头文主要声明了两个类, std::atomic 和 std::atomic_flag,另外还声明了一套 C 风格的原子类型和与 C 兼容的原子操作的函数。
  • <thread>
    • 该头文件主要声明了 std::thread 类,另外 std::this_thread 命名空间也在该头文件中。
  • <mutex>
    • 该头文件主要声明了与互斥量(mutex)相关的类,包括 std::mutex 系列类,std::lock_guard, std::unique_lock, 以及其他的类型和函数。
  • <condition_variable>
    • 该头文件主要声明了与条件变量相关的类,包括 std::condition_variable 和 std::condition_variable_any。
  • <future>
    • 该头文件主要声明了 std::promise, std::package_task 两个 Provider 类,以及 std::future 和 std::shared_future 两个 Future 类,另外还有一些与之相关的类型和函数,std::async() 函数就声明在此头文件中。

这里主要使用<thread><mutex>实现。

例子

根据线程执行的顺序,可以分为detachjoin

#include <iostream>
#include <thread>

using namespace std;

void output(int i)
{
    cout << "This thread number is " << i << endl;
    cout << "Thread " << i << " has finished" << endl;
}

int main()
{
    for (int i = 0; i < 5; i++)
    {
        thread t(output, i);
        t.detach(); //t.join();
    }
    getchar();
    return 0;
}

执行命令:g++ -std=c++0x test.cpp -pthread -o test

detach的结果为:

<

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值