Multi-threaded Pit--volatile

Source: Internet
Author: User
Tags volatile

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.