多线程中的volatile关键字

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 @   轩~邈  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示