In multithreaded programming, you should be careful when you open the optimization option or fall out of the pit.
Take a look at the following code, open two threads, the second thread set the loop condition of the first thread to false. Logically, this should end well, but if you use
g++-o3-o multithread Multithread.cpp-lpthread
Compile words TestThread1 is not come out, only g_brun plus volatile keyword to normal exit
Because G_brun is read into the register when TESTTHREAD1 is executed under the-O3 optimization option, the compiler discovers that there is no change to the G_brun in the function so that it does not go back to the memory to use the backup directly in the register, changing TestThread2 in G_ The brun value in memory has no effect on the G_brun register backup in TestThread1.
The addition of volatile means that the variable is not optimized every time the memory is taken to the value.
#include <pthread.h>#include <iostream>#include <unistd.h>using namespace std;//volatile bool g_brun = true;bool g_brun = true;void* TestThread1(void* arg){ cout << "TestThread1 进入" << endl; long long ll = 0; while(g_brun) ll ++; cout << "TestThread1 退出 ll:" << ll << endl;}void* TestThread2(void* arg){ cout << "TestThread2 进入" << endl; g_brun = false; cout << "TestThread2 退出 设置 g_brun = false" << endl;}int main(){ pthread_t threadId1; pthread_create(&threadId1, NULL, TestThread1, NULL); usleep(1000000); // 保证TestThread1先执行 pthread_t threadId2; pthread_create(&threadId2, NULL, TestThread2, NULL); pthread_join(threadId1,NULL); pthread_join(threadId2,NULL); return 0;}
Multi-threaded Pit--volatile