实际工作中遇到, 一个函数里面声明了静态变量, 而这个方法会被多线程调用, 会出现很多非预期的效果。所以今天整理记录下来。
先看一段程序。
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。
静态变量线程不安全是我们都知道的, 但是在不同环境下的差异 我们应该引起重视。