首页 > 编程语言 > 详细

C++ static变量是线程不安全造成的问题

时间:2020-07-01 16:34:12      阅读:111      评论:0      收藏:0      [点我收藏+]

实际工作中遇到, 一个函数里面声明了静态变量, 而这个方法会被多线程调用, 会出现很多非预期的效果。所以今天整理记录下来。

先看一段程序。

 1 #include <string>
 2 
 3 using namespace std;
 4 
 5 void* func(void* ptr)
 6 {
 7     static string str  = "2300000002836038413";
 8     for(int i = 0; i < 100000; i++)
 9     {
10         string str2 = "123";
11         str = str2;
12         str = str + test_str;
13         if (i % 3333 == 0)
14         {
15                 printf("i = %d \n", i);
16         }
17     }
18     return nullptr;
19 }
20 
21 int main()
22 {
23     printf("begin test \n");
24     pthread_t thread1, thread2;
25     pthread_create(&thread1, nullptr, func, nullptr);
26     pthread_create(&thread2, nullptr, func, nullptr);
27     pthread_join(thread1, nullptr);
28     pthread_join(thread2, nullptr);
29     printf("end test \n");
30     return 0;
31 }

在测试机器运行:

技术分享图片

 运行结果看不出什么异常来, 但是在服务器上, 却会异常core掉。 
如下图所示:

技术分享图片

仔细分析了core文件, 并没有发现什么信息。
技术分享图片

 后分析两台机器的环境发现   glibc的版本不一样。 

测试机器为:glibc-2.17-157
服务器为:glibc-2.12-1。

静态变量线程不安全是我们都知道的, 但是在不同环境下的差异  我们应该引起重视。 

 

C++ static变量是线程不安全造成的问题

原文:https://www.cnblogs.com/6-er-mi-hou/p/13219924.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!