当前位置: 首页 > news >正文

无锁队列实现(Michael Scott),伪代码与c++实现

一、Michael & Scoot 原版伪代码实现

structure pointer_t {ptr: pointer to node_t, count: unsigned integer}structure node_t {value: data type, next: pointer_t}structure queue_t {Head: pointer_t, Tail: pointer_t}initialize(Q: pointer to queue_t)node = new_node()		// Allocate a free nodenode->next.ptr = NULL	// Make it the only node in the linked listQ->Head.ptr = Q->Tail.ptr = node	// Both Head and Tail point to itenqueue(Q: pointer to queue_t, value: data type)E1:   node = new_node()	// Allocate a new node from the free listE2:   node->value = value	// Copy enqueued value into nodeE3:   node->next.ptr = NULL	// Set next pointer of node to NULLE4:   loop			// Keep trying until Enqueue is doneE5:      tail = Q->Tail	// Read Tail.ptr and Tail.count togetherE6:      next = tail.ptr->next	// Read next ptr and count fields togetherE7:      if tail == Q->Tail	// Are tail and next consistent?// Was Tail pointing to the last node?E8:         if next.ptr == NULL// Try to link node at the end of the linked listE9:            if CAS(&tail.ptr->next, next, <node, next.count+1>)E10:               break	// Enqueue is done.  Exit loopE11:            endifE12:         else		// Tail was not pointing to the last node// Try to swing Tail to the next nodeE13:            CAS(&Q->Tail, tail, <next.ptr, tail.count+1>)E14:         endifE15:      endifE16:   endloop// Enqueue is done.  Try to swing Tail to the inserted nodeE17:   CAS(&Q->Tail, tail, <node, tail.count+1>)dequeue(Q: pointer to queue_t, pvalue: pointer to data type): booleanD1:   loop			     // Keep trying until Dequeue is doneD2:      head = Q->Head	     // Read HeadD3:      tail = Q->Tail	     // Read TailD4:      next = head.ptr->next    // Read Head.ptr->nextD5:      if head == Q->Head	     // Are head, tail, and next consistent?D6:         if head.ptr == tail.ptr // Is queue empty or Tail falling behind?D7:            if next.ptr == NULL  // Is queue empty?D8:               return FALSE      // Queue is empty, couldn't dequeueD9:            endif// Tail is falling behind.  Try to advance itD10:            CAS(&Q->Tail, tail, <next.ptr, tail.count+1>)D11:         else		     // No need to deal with Tail// Read value before CAS// Otherwise, another dequeue might free the next nodeD12:            *pvalue = next.ptr->value// Try to swing Head to the next nodeD13:            if CAS(&Q->Head, head, <next.ptr, head.count+1>)D14:               break             // Dequeue is done.  Exit loopD15:            endifD16:         endifD17:      endifD18:   endloopD19:   free(head.ptr)		     // It is safe now to free the old nodeD20:   return TRUE                   // Queue was not empty, dequeue succeeded

二、C++实现

c++的实现就直接看上述的伪代码跟着实现即可,这里的一些atomic操作也可以看我之前写的博客

template<typename T>
class LockFreeQueue {
private:// 队列结构struct Node {std::shared_ptr<T> data;std::atomic<Node*> next;Node() : next(nullptr) {};};std::atomic<Node*> head; // 头节点std::atomic<Node*> tail; // 尾节点Node* dummy; // 用于回收节点的哑节点public:LockFreeQueue() {dummy = new Node();head.store(dummy);tail.store(dummy);}~LockFreeQueue() {T output;while (dequeue(output)) {}delete dummy;}// 禁止拷贝构造和赋值LockFreeQueue(const LockFreeQueue&) = delete;LockFreeQueue& operator=(const LockFreeQueue&) = delete;void enqueue(const T& value) {std::shared_ptr<T> new_data(std::make_shared<T>(value)); // 创建数据Node* new_node = new Node();  // 创建新节点Node* old_tail;while (true) {old_tail = tail.load();Node* next = old_tail->next.load();if (old_tail == tail.load()) { // 此时保证tail还没有被其他线程改变if (next == nullptr) { // 此时保证tail是队列的最后一个节点if (old_tail->next.compare_exchange_weak(next, new_node)) break; // 插入成功,这是一个原语,可以一次操作}else { // 说明tail落后了,推进tail指针tail.compare_exchange_weak(old_tail, next);}}}old_tail->data = new_data;tail.compare_exchange_weak(old_tail, new_node);}bool dequeue(T& value) {Node* old_head;while (true) {old_head = head.load();  // 获取当前头部节点Node* old_tail = tail.load();  // 获取当前尾部节点Node* next = old_head->next.load();if (old_head == head.load()) { // 确保head没有被改变if (old_head == old_tail) { // 队列为空,或者tail落后if (next == nullptr) { // 队列为空return false;}tail.compare_exchange_weak(old_tail, next);} else {// 从队列中移除head,并且读取其值if (next->data) {value = *(next->data);if (head.compare_exchange_weak(old_head, next)) break; // 清除head节点,退出循环}}}}delete old_head;return true;}
};

三、测试

测试代码如下:

int main() {LockFreeQueue<int> queue;std::thread t1([&queue](){for(int i=0; i<100; i++) {queue.enqueue(i);std::this_thread::sleep_for(std::chrono::milliseconds(100));}});std::thread t2([&queue](){for(int i=100; i<200; i++) {queue.enqueue(i);std::this_thread::sleep_for(std::chrono::milliseconds(100));}});std::thread t3([&queue]() {while (true) {int i = 0;if (queue.dequeue(i)) {std::cout << "t3:" << i << std::endl;}}});std::thread t4([&queue]() {while (true) {int i = 0;if (queue.dequeue(i)) {std::cout << "t4:" << i << std::endl;}}});t1.join();t2.join();t3.join();t4.join();
}

image-20241014161649144

可以看到,多线程下可以顺利的插入与找到数据

相关文章:

无锁队列实现(Michael Scott),伪代码与c++实现

一、Michael & Scoot 原版伪代码实现 structure pointer_t {ptr: pointer to node_t, count: unsigned integer}structure node_t {value: data type, next: pointer_t}structure queue_t {Head: pointer_t, Tail: pointer_t}initialize(Q: pointer to queue_t)node new_…...

猜数字小游戏

前言 猜数字游戏是一款经典且简单的互动游戏&#xff0c;常常用于提高逻辑思维能力和锻炼数学技巧。本文将深入探讨一段用 JavaScript 编写的猜数字游戏代码&#xff0c;帮助读者理解游戏的基本逻辑和实现方法。这段代码不仅适合初学者练习编程技巧&#xff0c;也是了解用户交…...

在Windows上搭建ChatTTS:从本地部署到远程AI音频生成全攻略

文章目录 前言1. 下载运行ChatTTS模型2. 安装Cpolar工具3. 实现公网访问4. 配置ChatTTS固定公网地址 前言 本篇文章主要介绍如何快速地在Windows系统电脑中本地部署ChatTTS开源文本转语音项目&#xff0c;并且我们还可以结合Cpolar内网穿透工具创建公网地址&#xff0c;随时随…...

如何用好 CloudFlare 的速率限制防御攻击

最近也不知道咋回事儿,群里好多站长都反映被CC 攻击了。有人说依旧是 PCDN 干的,但明月感觉不像,因为有几个站长被 CC 攻击都是各种动态请求(这里的动态请求指的是.php 文件的请求)。经常被攻击的站长们都知道,WordPress /Typecho 这类动态博客系统最怕的就是这种动态请求…...

Unity3D 立方体纹理与自制天空盒详解

立方体纹理和自制天空盒是游戏开发中常用的技术之一&#xff0c;可以为游戏增添更加丰富的视觉效果。在本文中&#xff0c;我们将详细介绍Unity3D中立方体纹理和自制天空盒的使用方法&#xff0c;并给出相应的代码实现。 对惹&#xff0c;这里有一个游戏开发交流小组&#xff…...

【工具】VSCODE下载,配置初次设置

打开 settings.json 文件&#xff0c;包含了 Visual Studio Code (VSCode) 中的各种用户配置。 {"files.associations": {"*.vue": "vue","*.wpy": "vue","*.wxml": "html","*.wxss": "…...

vue使用jquery的ajax,页面跳转

一、引入jquery依赖 打开终端更新npm npm install -g npm 更新完后引入输入npm install jquery 加载完后 在最外层的package.json文件中加入以下代码 配置好后导入jquery 设置变量用于接收服务器传输的数据 定义ajax申请数据 服务器的Controller层传输数据 &#xff08;…...

基于微信小程序的社区二手交易系统的详细设计和实现(源码+lw+部署文档+讲解等)

项目运行截图 技术框架 后端采用SpringBoot框架 Spring Boot 是一个用于快速开发基于 Spring 框架的应用程序的开源框架。它采用约定大于配置的理念&#xff0c;提供了一套默认的配置&#xff0c;让开发者可以更专注于业务逻辑而不是配置文件。Spring Boot 通过自动化配置和约…...

D34【python 接口自动化学习】- python基础之输入输出与文件操作

day34 文件关闭 学习日期&#xff1a;20241011 学习目标&#xff1a;输入输出与文件操作&#xfe63;-46 常见常新&#xff1a;文件的关闭 学习笔记&#xff1a; 文件关闭的内部工作过程 close&#xff08;&#xff09;函数 with语句 常用的打开关闭文件 # 文件关闭 # 方式…...

【Linux系列】set -euo pipefail 命令详解

&#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学…...

【Python爬虫实战】正则:中文匹配与贪婪非贪婪模式详解

&#x1f308;个人主页&#xff1a;https://blog.csdn.net/2401_86688088?typeblog &#x1f525; 系列专栏&#xff1a;https://blog.csdn.net/2401_86688088/category_12797772.html 目录 前言 一、匹配中文 &#xff08;一&#xff09;匹配单个中文字符 &#xff08;二…...

保护数据安全:JS前端加密与PHP后端解密实战教程,让敏感信息更安全

保护数据安全&#xff1a;JS前端加密与PHP后端解密实战教程&#xff0c;让敏感信息更安全 在Web开发中&#xff0c;确保用户提交的敏感信息&#xff08;如密码、手机号码等&#xff09;的安全性是非常重要的。一种常见的做法是使用加密技术来保护这些数据&#xff0c;在传输过…...

72 分布式锁

72 分布式锁 什么是分布式锁 分布式锁 分布式 锁。那么分布式是指的什么呢&#xff1f;锁又是锁的谁呢&#xff1f;在业务开发中我们经常会听到分布式分布式的概念&#xff0c;分布式也很简单&#xff0c;通俗的来说就是你具有多个服务器&#xff0c;每个服务器上运行的程序…...

使用Windbg分析dump文件排查C++软件异常的一般步骤与要点分享

目录 1、概述 2、打开dump文件&#xff0c;查看发生异常的异常类型码 3、查看发生异常的那条汇编指令 3.1、汇编代码能最直接、最本真的反映出崩溃的原因 3.2、汇编指令中访问64KB小地址内存区&#xff0c;可能是访问了空指针 3.3、汇编指令中访问了很大的内核态的内存地…...

30 天 Python 3 学习计划

30 天 Python 3 学习计划 https://www.runoob.com/python3/python3-tutorial.html 1. Python3 基础语法 2. Python3 基本数据类型 3. Python3 数据类型转换 4. Python3 解释器 5. Python3 注释 6. Python3 运算符 7. Python3 数字(Number) 8. Python3 字符串 …...

【MATLAB实例】批量提取.csv数据并根据变量名筛选

【MATLAB实例】批量提取.csv数据并根据变量名筛选 准备&#xff1a;数据说明MATLAB批量提取参考 准备&#xff1a;数据说明 .csv数据如下&#xff1a; 打开某表格数据&#xff0c;如下&#xff1a;&#xff08;需要说明的是此数据含表头&#xff09; 需求说明&#xff1a;需…...

【软件】Ubuntu下QT的安装和使用

【软件】Ubuntu下QT的安装和使用 零、前言 QT是应用得比较广泛的程序框架&#xff0c;是因为其跨平台特性比较好&#xff0c;且用C/C作为开发语言&#xff0c;性能也比较好&#xff0c;故本文介绍如何安装和使用QT&#xff0c;用的版本是QT 6.2.4&#xff0c;由于QT在Windows…...

在Spring Boot中具有多个实现的接口正确注入的六种方式

​ 博客主页: 南来_北往 系列专栏&#xff1a;Spring Boot实战 在Spring Boot中&#xff0c;当一个接口具有多个实现时&#xff0c;正确地将这些实现注入到需要使用它们的地方是一个常见的需求。以下是在Spring Boot中实现这一目标的六种方式&#xff1a; 1. 使用Autowir…...

登陆微软账户太慢了,如何解决

软账号登录慢解决办法&#xff1a; 打开“网络和Internet”选择“以太网”选择“更改适配器选项”选择现用网络&#xff0c;右键->属性选择“IPV4”右键属性更改DNS地址为以下两者4.2.2.14.2.2.2...

Vue3动态组件component不生效问题解决方法

问题&#xff1a; vue3循环渲染动态组件component不生效&#xff0c;页面空白 在vue3使用component动态组件展示组件时&#xff0c;组件就是不展示显示空白。在vue2中使用动态变量component展示组件都是没问题。试了很多方法 踩了很多坑&#xff0c;所以记录下&#xff1a; 登录…...

Linux应用开发之网络套接字编程(实例篇)

服务端与客户端单连接 服务端代码 #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <pthread.h> …...

进程地址空间(比特课总结)

一、进程地址空间 1. 环境变量 1 &#xff09;⽤户级环境变量与系统级环境变量 全局属性&#xff1a;环境变量具有全局属性&#xff0c;会被⼦进程继承。例如当bash启动⼦进程时&#xff0c;环 境变量会⾃动传递给⼦进程。 本地变量限制&#xff1a;本地变量只在当前进程(ba…...

Python爬虫(二):爬虫完整流程

爬虫完整流程详解&#xff08;7大核心步骤实战技巧&#xff09; 一、爬虫完整工作流程 以下是爬虫开发的完整流程&#xff0c;我将结合具体技术点和实战经验展开说明&#xff1a; 1. 目标分析与前期准备 网站技术分析&#xff1a; 使用浏览器开发者工具&#xff08;F12&…...

linux 下常用变更-8

1、删除普通用户 查询用户初始UID和GIDls -l /home/ ###家目录中查看UID cat /etc/group ###此文件查看GID删除用户1.编辑文件 /etc/passwd 找到对应的行&#xff0c;YW343:x:0:0::/home/YW343:/bin/bash 2.将标红的位置修改为用户对应初始UID和GID&#xff1a; YW3…...

【OSG学习笔记】Day 16: 骨骼动画与蒙皮(osgAnimation)

骨骼动画基础 骨骼动画是 3D 计算机图形中常用的技术&#xff0c;它通过以下两个主要组件实现角色动画。 骨骼系统 (Skeleton)&#xff1a;由层级结构的骨头组成&#xff0c;类似于人体骨骼蒙皮 (Mesh Skinning)&#xff1a;将模型网格顶点绑定到骨骼上&#xff0c;使骨骼移动…...

OpenLayers 分屏对比(地图联动)

注&#xff1a;当前使用的是 ol 5.3.0 版本&#xff0c;天地图使用的key请到天地图官网申请&#xff0c;并替换为自己的key 地图分屏对比在WebGIS开发中是很常见的功能&#xff0c;和卷帘图层不一样的是&#xff0c;分屏对比是在各个地图中添加相同或者不同的图层进行对比查看。…...

Linux --进程控制

本文从以下五个方面来初步认识进程控制&#xff1a; 目录 进程创建 进程终止 进程等待 进程替换 模拟实现一个微型shell 进程创建 在Linux系统中我们可以在一个进程使用系统调用fork()来创建子进程&#xff0c;创建出来的进程就是子进程&#xff0c;原来的进程为父进程。…...

深度学习习题2

1.如果增加神经网络的宽度&#xff0c;精确度会增加到一个特定阈值后&#xff0c;便开始降低。造成这一现象的可能原因是什么&#xff1f; A、即使增加卷积核的数量&#xff0c;只有少部分的核会被用作预测 B、当卷积核数量增加时&#xff0c;神经网络的预测能力会降低 C、当卷…...

什么是VR全景技术

VR全景技术&#xff0c;全称为虚拟现实全景技术&#xff0c;是通过计算机图像模拟生成三维空间中的虚拟世界&#xff0c;使用户能够在该虚拟世界中进行全方位、无死角的观察和交互的技术。VR全景技术模拟人在真实空间中的视觉体验&#xff0c;结合图文、3D、音视频等多媒体元素…...

抽象类和接口(全)

一、抽象类 1.概念&#xff1a;如果⼀个类中没有包含⾜够的信息来描绘⼀个具体的对象&#xff0c;这样的类就是抽象类。 像是没有实际⼯作的⽅法,我们可以把它设计成⼀个抽象⽅法&#xff0c;包含抽象⽅法的类我们称为抽象类。 2.语法 在Java中&#xff0c;⼀个类如果被 abs…...