C++ static變量是線程不安全造成的問題


實際工作中遇到, 一個函數里面聲明了靜態變量, 而這個方法會被多線程調用, 會出現很多非預期的效果。所以今天整理記錄下來。

先看一段程序。

 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。

靜態變量線程不安全是我們都知道的, 但是在不同環境下的差異  我們應該引起重視。 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM