1、Volatile 单词

①(人或其情绪)不稳定的;易变的;易怒的,喜怒无常的

②(情况)可能急剧波动的;不稳定的;易恶化的

③(物质)易挥发的,易气化的

④(计算机内存)易失的

 

2、问题代码示例

#include <stdio.h>
#include <pthread.h>

int sharedValue = 0;

void *threadFunction(void *arg) 
{
    sharedValue = 10;
    return NULL;
}

int main() 
{
    pthread_t thread;
    pthread_create(&thread, NULL, threadFunction, NULL);

    while (sharedValue != 10) 
    {
        // 等待线程修改sharedValue
    }

    printf("sharedValue has been modified.\n");

    pthread_join(thread, NULL);

    return 0;
}

① 无代码优化:

xuanmiao@linux:~/Test$ gcc test.c -o test -lpthread
xuanmiao@linux:~/Test$ ./test
sharedValue has been modified.

 ② O3级别编译优化 

xuanmiao@linux:~/Test$ gcc test.c -o test -lpthread -O3
xuanmiao@linux:~/Test$ ./test

 

🏠 为什么编译优化后,代码进入了while死循环呢?

答:编译优化时,编译器认为在while循环中sharedValue的值不会发生改变 ,编译器将sharedValue值缓存到寄存器中,

寄存器中的sharedValue值一直没有发生变化,且主线程只会读取寄存器中的值,所以陷入死循环。

 

3、使用volatile关键字

#include <stdio.h>
#include <pthread.h>

volatile int sharedValue = 0;

void *threadFunction(void *arg) 
{
    sharedValue = 10;
    return NULL;
}

int main() 
{
    pthread_t thread;
    pthread_create(&thread, NULL, threadFunction, NULL);

    while (sharedValue != 10) 
    {
        // 等待线程修改sharedValue
    }

    printf("sharedValue has been modified.\n");

    pthread_join(thread, NULL);

    return 0;
}

执行结果:

xuanmiao@linux:~/Test$ gcc test.c -o test -lpthread -O3
xuanmiao@linux:~/Test$ ./test
sharedValue has been modified.

volatile 关键字告诉编译器,sharedValue 的值可能会在程序外部被修改(例如,被其他线程修改),因此编译器不会将 sharedValue 的值缓存到寄存器中,而是每次访问时都从内存中读取。

posted on 2025-02-26 22:50  轩~邈  阅读(15)  评论(0)    收藏  举报