与AI合作 -- 单例工厂2遗留的问题:bard的错误

问题

上一节我们针对函数内静态变量初始化在多线程环境中要不要用锁保护提出了疑问,代码如下:


class Singleton {
public:static Singleton& getInstance() {std::lock_guard<std::mutex> lock(mutex); // Acquire lock for thread safetystatic Singleton instance; // Local static variable for thread safetyreturn instance;

结论

不必。C++11已经自己加锁了。

__cxa_guard_acquire

为了简单,我们先简单写个试验程序:

class Product {
public:Product(){std::cout<<"Product constructor"<<std::endl;}
};void test(){std::cout<<"I am in test()"<<std::endl;static Product pro;std::cout<<"leaving test()"<<std::endl;
}int main() {std::thread first(test);std::thread second(test);first.join();second.join();test();return 0;
}

直接用GDB或者objdump看下test函数对应的汇编:

(gdb) disass test
Dump of assembler code for function test():0x0000000000400e26 <+0>:     push   %rbp0x0000000000400e27 <+1>:     mov    %rsp,%rbp0x0000000000400e2a <+4>:     push   %r120x0000000000400e2c <+6>:     push   %rbx0x0000000000400e2d <+7>:     mov    $0x401808,%esi0x0000000000400e32 <+12>:    mov    $0x6030c0,%edi0x0000000000400e37 <+17>:    callq  0x400ca0 <_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@plt>0x0000000000400e3c <+22>:    mov    $0x400c40,%esi0x0000000000400e41 <+27>:    mov    %rax,%rdi0x0000000000400e44 <+30>:    callq  0x400cd0 <_ZNSolsEPFRSoS_E@plt>0x0000000000400e49 <+35>:    movzbl 0x202390(%rip),%eax        # 0x6031e0 <_ZGVZ4testvE3pro>0x0000000000400e50 <+42>:    test   %al,%al0x0000000000400e52 <+44>:    sete   %al0x0000000000400e55 <+47>:    test   %al,%al0x0000000000400e57 <+49>:    je     0x400e86 <test()+96>0x0000000000400e59 <+51>:    mov    $0x6031e0,%edi0x0000000000400e5e <+56>:    callq  0x400d20 <__cxa_guard_acquire@plt>0x0000000000400e63 <+61>:    test   %eax,%eax0x0000000000400e65 <+63>:    setne  %al0x0000000000400e68 <+66>:    test   %al,%al0x0000000000400e6a <+68>:    je     0x400e86 <test()+96>0x0000000000400e6c <+70>:    mov    $0x0,%r12d0x0000000000400e72 <+76>:    mov    $0x6031d9,%edi0x0000000000400e77 <+81>:    callq  0x40103a <Product::Product()>0x0000000000400e7c <+86>:    mov    $0x6031e0,%edi0x0000000000400e81 <+91>:    callq  0x400c70 <__cxa_guard_release@plt>0x0000000000400e86 <+96>:    mov    $0x401817,%esi0x0000000000400e8b <+101>:   mov    $0x6030c0,%edi0x0000000000400e90 <+106>:   callq  0x400ca0 <_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@plt>0x0000000000400e95 <+111>:   mov    $0x400c40,%esi0x0000000000400e9a <+116>:   mov    %rax,%rdi0x0000000000400e9d <+119>:   callq  0x400cd0 <_ZNSolsEPFRSoS_E@plt>0x0000000000400ea2 <+124>:   jmp    0x400ec1 <test()+155>0x0000000000400ea4 <+126>:   mov    %rax,%rbx0x0000000000400ea7 <+129>:   test   %r12b,%r12b0x0000000000400eaa <+132>:   jne    0x400eb6 <test()+144>0x0000000000400eac <+134>:   mov    $0x6031e0,%edi0x0000000000400eb1 <+139>:   callq  0x400c60 <__cxa_guard_abort@plt>0x0000000000400eb6 <+144>:   mov    %rbx,%rax0x0000000000400eb9 <+147>:   mov    %rax,%rdi0x0000000000400ebc <+150>:   callq  0x400d10 <_Unwind_Resume@plt>0x0000000000400ec1 <+155>:   pop    %rbx0x0000000000400ec2 <+156>:   pop    %r120x0000000000400ec4 <+158>:   pop    %rbp0x0000000000400ec5 <+159>:   retq

简单提一下_ZGVZ4testvE3pro demangle一下(第一次值是0,初始化后是1):

[mzhai@singletonFactoryAi]$ c++filt _ZGVZ4testvE3pro
guard variable for test()::pro

 着重看下面的__cxa_guard_acquire

看到__cxa_guard_acquire、__cxa_guard_release没?中间夹着Product::Product()

即使没见过这两个函数,也能猜到和static变量初始化有关,防止多个线程同时初始化一个静态变量. 这是我把__cxa_guard_acquire输入搜索引擎搜到的:

C++ constructor guards for static instances

Introduction

The libstd++ ABI requires implementations of the following functions:

int __cxa_guard_acquire(__guard *g);

void __cxa_guard_release(__guard *g);

void __cxa_guard_abort(__guard *g);

These functions are not intended to be ever used by the programmer, instead the C++ compiler will emit code calling them if statically allocated class instances are used. In a multi-threaded environment special care needs to be taken to prevent race conditions while initializing and using such instances. This modules provides them.

Usage

This module is intended to be used by platforms that want to provide C++ support, but the used standard C++ library does not provide these guards. In this case, adding this module will do the trick. The programmer / user should never interact with any of the functions.

Note that on some platforms the type __guard is defined differently from the "generic" definition, most notably ARM. For those platforms a header named cxx_ctor_guards_arch.h needs to be created containing the correct typedef and the preprocessor macro CXX_CTOR_GUARDS_CUSTOM_TYPE needs to be defined.

https://opensource.apple.com/source/libcppabi/libcppabi-14/src/cxa_guard.cxx 

int __cxxabiv1::__cxa_guard_acquire(uint64_t* guard_object)
{// Double check that the initializer has not already been runif ( initializerHasRun(guard_object) )return 0;// We now need to acquire a lock that allows only one thread// to run the initializer.  If a different thread calls// __cxa_guard_acquire() with the same guard object, we want // that thread to block until this thread is done running the // initializer and calls __cxa_guard_release().  But if the same// thread calls __cxa_guard_acquire() with the same guard object,// we want to abort.  // To implement this we have one global pthread recursive mutex // shared by all guard objects, but only one at a time.  

用GDB 模拟race condition

如果读者感兴趣,可以调试一下我们给出的程序:

(gdb) b __cxa_guard_acquire       使得两个线程都停在__cxa_guard_acquire
Breakpoint 2 at 0x7ffff7acf980
(gdb) r
Continuing.
Thread 2 "a.out" hit Breakpoint 2, 0x00007ffff7acf980 in __cxa_guard_acquire () from /lib64/libstdc++.so.6Thread 3 "a.out" hit Breakpoint 2, 0x00007ffff7acf980 in __cxa_guard_acquire () from /lib64/libstdc++.so.6
Quit(gdb) where
Selected thread is running.(gdb) info thread                2、3线程都停在了__cxa_guard_acquireId   Target Id                                   Frame
* 1    Thread 0x7ffff7fe1740 (LWP 2468153) "a.out" (running)2    Thread 0x7ffff6eb9700 (LWP 2468165) "a.out" 0x00007ffff7acf980 in __cxa_guard_acquire () from /lib64/libstdc++.so.63    Thread 0x7ffff66b8700 (LWP 2468166) "a.out" 0x00007ffff7acf980 in __cxa_guard_acquire () from /lib64/libstdc++.so.6(gdb) b Product::Product thread 2       
Breakpoint 3 at 0x401046: file static_var_in_func.cpp, line 36.
(gdb) thread apply 2 c            让第二个线程获得锁,先停在静态变量初始化中
Thread 2 (Thread 0x7ffff6eb9700 (LWP 2468165)):
Continuing.
Thread 2 "a.out" hit Breakpoint 3, Product::Product (this=0x6031d9 <test()::pro>) at static_var_in_func.cpp:36
36                      std::cout<<"Product constructor"<<std::endl;(gdb) thread apply 3 c            让第三个线程(还没获得锁)继续运行,应该卡在__cxa_guard_acquire 
Thread 3 (Thread 0x7ffff66b8700 (LWP 2468166)):
Continuing.
^C
Thread 1 "a.out" received signal SIGINT, Interrupt.
0x00007ffff78226cd in __pthread_timedjoin_ex () from /lib64/libpthread.so.0
(gdb) thread 3
[Switching to thread 3 (Thread 0x7ffff66b8700 (LWP 2468166))](running)
(gdb) where
Selected thread is running.
(gdb) interrupt
(gdb)
Thread 3 "a.out" stopped.
0x00007ffff72759bd in syscall () from /lib64/libc.so.6
Quit
(gdb) where                       正如预期,第三个线程卡在获得锁上
#0  0x00007ffff72759bd in syscall () from /lib64/libc.so.6
#1  0x00007ffff7acfa3f in __cxa_guard_acquire () from /lib64/libstdc++.so.6
#2  0x0000000000400e63 in test () at static_var_in_func.cpp:42
#3  0x0000000000401205 in std::__invoke_impl<void, void (*)()> (__f=@0x616008: 0x400e26 <test()>) at /usr/include/c++/8/bits/invoke.h:60
#4  0x0000000000401085 in std::__invoke<void (*)()> (__fn=@0x616008: 0x400e26 <test()>) at /usr/include/c++/8/bits/invoke.h:95
#5  0x00000000004016d4 in std::thread::_Invoker<std::tuple<void (*)()> >::_M_invoke<0ul> (this=0x616008) at /usr/include/c++/8/thread:244
#6  0x00000000004016aa in std::thread::_Invoker<std::tuple<void (*)()> >::operator() (this=0x616008) at /usr/include/c++/8/thread:253
#7  0x000000000040168e in std::thread::_State_impl<std::thread::_Invoker<std::tuple<void (*)()> > >::_M_run (this=0x616000) at /usr/include/c++/8/thread:196
#8  0x00007ffff7afbb23 in execute_native_thread_routine () from /lib64/libstdc++.so.6
#9  0x00007ffff78211ca in start_thread () from /lib64/libpthread.so.0
#10 0x00007ffff7275e73 in clone () from /lib64/libc.so.6

AI的回答

mzhai: Assume there is a static variable A which is an object of a class, this static variable is defined in a function named funA. When is A initialized? and is there a race condition if two threads call funA concurrently?

ChatGPT: In C++, static variables inside functions (local static variables) are initialized the first time the program execution encounters their declaration within that function. They're initialized in a thread-safe manner in compliance with the C++11 standard.

For instance, if you have a function funA with a static variable A inside it, like this:

void funA() { static MyClass A; // ... } 

When funA is called for the first time, the static MyClass A; line will be executed. This initialization occurs once, and subsequent calls to funA won't reinitialize A. This initialization is thread-safe in C++11 and later, meaning the standard guarantees that it will be properly handled in a multi-threaded context. There won't be a race condition during this initialization.

Bard

Here's a breakdown of the initialization and potential race condition:

1. Initialization of static variable A:

  • When: The static variable A will be initialized the first time control flow reaches its declaration within funA, even if it's not explicitly used in that particular call.
  • How: The constructor of the class will be invoked to initialize A's members.
  • Subsequent calls: In subsequent calls to funA, the already initialized instance of A will be used, and the constructor won't be called again.

2. Race condition in multi-threaded environment:

  • Yes, a race condition can occur if two threads call funA concurrently before A has been initialized.
  • Scenario:
    • Both threads enter funA for the first time.
    • Both threads see that A hasn't been initialized yet.
    • Both threads attempt to create an instance of A, leading to multiple initializations and potential data corruption or crashes.

 可见在这方面Bard不如Chat GPT正确。

他山之石

后来搜到一篇外文博客,读者可以作为参考。Adventures in Systems Programming: C++ Local Statics - In Pursuit of Laziness

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/609768.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

LeetCode[102] 二叉树层序遍历

Description&#xff1a;给你二叉树的根节点 root &#xff0c;返回其节点值的 层序遍历 。 &#xff08;即逐层地&#xff0c;从左到右访问所有节点&#xff09;。解法&#xff1a; vector<vector<int>> levelOrder(TreeNode* root) {vector<vector<int>…

第一次面试总结 - 迈瑞医疗 - 软件测试

&#x1f9f8;欢迎来到dream_ready的博客&#xff0c;&#x1f4dc;相信您对专栏 “本人真实面经” 很感兴趣o (ˉ▽ˉ&#xff1b;) 专栏 —— 本人真实面经&#xff0c;更多真实面试经验&#xff0c;中大厂面试总结等您挖掘 注&#xff1a;此次面经全靠小嘴八八&#xff0c;没…

大数据版本管理工具数据湖文件存储系统LakeFS客户端的安装和配置使用

LakeFS是一个开源的数据湖文件存储系统&#xff0c;它提供了版本控制和数据管理的功能。本文将介绍如何安装和配置LakeFS客户端。 首先&#xff0c;你需要确保已经安装了Python环境。LakeFS的客户端使用Python编写&#xff0c;因此需要安装Python来运行客户端。 安装LakeFS客…

腾讯云最新优惠活动入口整理汇总

随着云计算技术的快速发展&#xff0c;腾讯云作为国内领先的云服务提供商&#xff0c;一直致力于为用户提供高效、稳定、安全的云服务。为了回馈广大用户的支持&#xff0c;腾讯云经常推出各种优惠活动。本文将对腾讯云最新的优惠活动入口进行整理和汇总&#xff0c;帮助用户更…

《系统架构设计师教程(第2版)》第3章-信息系统基础知识-08-典型信息系统架构模型(电子政务、电子商务)

文章目录 1. 企业信息化与电子政务1.1 电子政务的概念1.2 三个组成部分1.3 电子政务的内容(重点)1)政府与政府2)政府对企/事业单位3)政府对居民4)企业对政府5)居民对政府1.4 电子政务的发展阶段。1)起步阶段2)政府与用户单向互动3)政府与用户双向互动4)网上事务处理…

【CV】计算两个向量的夹角,并使用 OpenCV 可视化弧线

背景 基于人体/动物&#xff0c;骨骼点数据&#xff0c;计算关节角度 1. 原理 计算两个向量的夹角&#xff0c;我们已三个点为例&#xff0c;BA 向量和BC向量&#xff0c;求 B 的角度。若为四个点&#xff0c;延长交叉即可。 2. 效果 效果图如下 3. 核心代码 def comput…

【服务器数据恢复】FreeNAS+ESXi数据恢复案例

服务器数据恢复环境&#xff1a; 一台服务器&#xff0c;虚拟化系统为esxi&#xff0c;上层使用iSCSI的方式实现FC SAN功能&#xff0c;iSCSI通过FreeNAS构建。 FreeNAS采用了UFS2文件系统&#xff0c;esxi虚拟化系统里有3台虚拟机&#xff1a;其中一台虚拟机安装FreeBSD系统&a…

[足式机器人]Part3 机构运动学与动力学分析与建模 Ch00-2(2) 质量刚体的在坐标系下运动

本文仅供学习使用&#xff0c;总结很多本现有讲述运动学或动力学书籍后的总结&#xff0c;从矢量的角度进行分析&#xff0c;方法比较传统&#xff0c;但更易理解&#xff0c;并且现有的看似抽象方法&#xff0c;两者本质上并无不同。 2024年底本人学位论文发表后方可摘抄 若有…

开发基础----牛客SQL速成

SQL练习题解 一.单表查询(非技术快速入门)1.基础查询SQL1 查询所有列SQL2 查询多列SQL3 查询结果去重SQL4 查询结果限制返回行数SQL5 将查询后的列重新命名SQL6 查找学校是北大的学生信息SQL7 查找年龄大于24岁的用户信息SQL8 查找某个年龄段的用户信息SQL9 查找除复旦大学的用…

redis的高可用(主从复制、哨兵、群集)

redis的高可用&#xff08;主从复制、哨兵、群集&#xff09; 主从复制&#xff1a;主从复制是高可用Redis的基础&#xff0c;哨兵和集群都是在主从复制基础上实现高可用的。主从复制主要实现了数据的多机备份&#xff0c;以及对于读操作的负载均衡和简单的故障恢复。缺陷&…

使用 LLVM clang C/C++ 编译器编译 OpenSSL 3.X库

1、下载 OpenSSL 3.X 库的源代码放到待编译目录 2、解压并接入 OpenSSL 3.X 库源码的根目录 3、复制 ./Configure 一个取名为 ./Configure-clang 4、修改 ./Configure-clang 找到配置段&#xff1a; CC CXX CPP LD 把它们改成 CC > "/usr/bin/clang-…

JavaScript 地址信息与页面跳转

在JavaScript中&#xff0c;你可以使用各种方法来处理地址信息并进行页面跳转。以下是一些常见的方法&#xff1a; 1.使用window.location对象&#xff1a; window.location对象包含了当前窗口的URL信息&#xff0c;并且可以用来进行页面跳转。 * 获取URL的某一部分&#xf…

【python】爬取豆瓣电影排行榜Top250存储到Excel文件中【附源码】

英杰社区https://bbs.csdn.net/topics/617804998 一、背景 近年来&#xff0c;Python在数据爬取和处理方面的应用越来越广泛。本文将介绍一个基于Python的爬虫程 序&#xff0c;用于抓取豆瓣电影Top250的相关信息&#xff0c;并将其保存为Excel文件。 程序包含以下几个部…

Qt UI框架和Duilib UI框架差别

Qt UI框架和Duilib UI框架在以下几个方面存在差异: 跨平台性:Qt是一个跨平台的UI工具包,可以在不同的操作系统上运行,如Windows、Linux和Mac OS X。而Duilib主要针对Windows系统,其跨平台能力相对较弱。 功能和性能:Qt作为一个成熟的框架,提供了丰富的功能和性能,包括对…

[游戏开发] 两向量夹角计算(0-360度)

上图是Unity左手坐标系&#xff0c;红轴是右&#xff0c;蓝轴是前&#xff0c;绿轴是上 测试目标是黑(3.54,0,4)、黄(-3.85,0,4.8)、灰(0.46,0,-2.6)三个向量&#xff0c;且三个向量都再XZ平面上&#xff0c;Y的值为0 以黑色为起始轴&#xff0c;和其他两周做角度计算 计算角…

微信小程序如何自定义导航栏,怎么确定导航栏及状态栏的高度?导航栏被刘海、信号图标给覆盖了怎么办?

声明&#xff1a;本文为了演示效果&#xff0c;颜色采用的比较显眼&#xff0c;可根据实际情况修改颜色 问题描述 当我们在JSON中将navigationStyle设置成custom后&#xff0c;当前页面的顶部导航栏就需要我们制作了&#xff0c;但出现了一下几个问题&#xff1a; 导航栏的高…

Day29 回溯算法part05 491. 非递减子序列 46. 全排列 47. 全排列 II

回溯算法part05 491. 非递减子序列 46. 全排列 47. 全排列 II 491. 非递减子序列 class Solution { private:vector<vector<int>> result;vector<int> path; public:void backTracing(vector<int>& nums,int startIndex){if(path.size()>1) …

【Scala】——流程控制

1 if-else 分支控制 让程序有选择的的执行&#xff0c;分支控制有三种&#xff1a;单分支、双分支、多分支 1.1单分支 if (条件表达式) {执行代码块 }1.2 双分支 if (条件表达式) {执行代码块 1 } else {执行代码块 2 }1.3 多分支 if (条件表达式1) {执行代码块 1 } else …

初学者的基本 Python 面试问题和答案

文章目录 专栏导读1、什么是Python&#xff1f;列出 Python 在技术领域的一些流行应用。2、在目前场景下使用Python语言作为工具有什么好处&#xff1f;3、Python是编译型语言还是解释型语言&#xff1f;4、Python 中的“#”符号有什么作用&#xff1f;5、可变数据类型和不可变…

GSP算法在数据挖掘中的应用

文章目录 一&#xff1a;基本概念介绍二&#xff1a;从一个样例入手三 论文中定义的一些细节四&#xff1a;GSP算法五.算法六 源代码及数据集等总结七. 参考文章 一&#xff1a;基本概念介绍 序列模式挖掘&#xff1a;指挖掘相对时间或其他模式出现频率高的模式 序列模式挖掘…