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 的值缓存到寄存器中,而是每次访问时都从内存中读取。

 

volatile关键字可以保证读写变量都到内存中读写,但是不能保证程序指令重排序,程序仍然可能存在并发性问题

// reordering_demo.c - 演示 volatile 不能完全防止重排序
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

volatile int flag = 0;
volatile int data = 0;
int reorder_detected = 0;

void *writer_thread(void *arg) 
{
    // 写入操作
    data = 100;
    flag = 1;  // volatile 不能保证之前的写入不会重排序到后面
    return NULL;
}

void *reader_thread(void *arg) 
{
    int local_flag, local_data;
    
    // 等待 flag 被设置
    while (flag == 0) {
        // 等待
    }
    
    local_data = data;
    local_flag = flag;
    
    // 理论上 data 应该是 100,但由于可能的指令重排序,可能不是
    if (local_data != 100 && local_flag == 1) {
        reorder_detected = 1;
        printf("检测到重排序!data=%d, flag=%d\n", local_data, local_flag);
    }
    
    return NULL;
}

int main() 
{
    pthread_t writer, reader;
    int i;
    int reorder_count = 0;
    int test_count = 10000;
    
    printf("开始测试 %d 次,检测指令重排序...\n", test_count);
    printf("注意:在 x86 架构上很难复现,这主要演示 volatile 的局限性\n\n");
    
    for (i = 0; i < test_count; i++) {
        // 重置变量
        data = 0;
        flag = 0;
        
        // 创建线程
        pthread_create(&writer, NULL, writer_thread, NULL);
        pthread_create(&reader, NULL, reader_thread, NULL);
        
        // 等待线程结束
        pthread_join(writer, NULL);
        pthread_join(reader, NULL);
        
        if (reorder_detected) {
            reorder_count++;
            reorder_detected = 0;
        }
        
        if ((i + 1) % 1000 == 0) {
            printf("已完成 %d 次测试\n", i + 1);
        }
    }
    
    printf("\n测试结果:\n");
    printf("总测试次数:%d\n", test_count);
    printf("检测到重排序次数:%d\n", reorder_count);
    printf("重排序比例:%.2f%%\n", (float)reorder_count / test_count * 100);
    printf("\n结论:volatile 不能完全防止指令重排序,");
    printf("需要使用内存屏障或原子操作\n");
    
    return 0;
}
Writer 线程 (生产者) Reader 线程 (消费者)
1. 执行 data = 100; (意图:先写数据) 1. 进入 while (flag == 0) 循环 (忙等待,不断读取 flag)
2. 执行 flag = 1; (意图:后发信号) 2. 情况 A (正常): 检测到 flag 变为 1,跳出循环。 情况 B (重排序/延迟): 由于 CPU 乱序或缓存未同步,可能先看到 flag=1,但此时 data 的更新还没对当前核心可见。
3. 线程结束返回。 3. 执行 local_data = data; (读取数据)
  4. 执行 local_flag = flag;
  5. 检测逻辑: if (local_data != 100 && local_flag == 1) 如果成立,说明看到了标志位却没看到数据 -> 重排序发生! 设置 reorder_detected = 1 并打印错误信息。
  6. 线程结束返回。

 

采用原子操作改写代码:

// atomic_reordering_demo.c - 使用原子操作防止重排序
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdatomic.h>

// 使用原子变量
atomic_int flag = 0;
atomic_int data = 0;
int reorder_detected = 0;

void *writer_thread(void *arg) 
{
    // 使用 release 语义:保证之前的写操作不会被重排序到后面
    atomic_store_explicit(&data, 100, memory_order_release);
    atomic_store_explicit(&flag, 1, memory_order_release);
    return NULL;
}

void *reader_thread(void *arg) 
{
    int local_flag, local_data;
    
    // 使用 acquire 语义:保证之后的读操作不会被重排序到前面
    while (atomic_load_explicit(&flag, memory_order_acquire) == 0) {
        // 等待 flag 被设置
    }
    
    local_data = atomic_load_explicit(&data, memory_order_acquire);
    local_flag = atomic_load_explicit(&flag, memory_order_acquire);
    
    // 由于使用了 acquire-release 语义,data 一定是 100
    if (local_data != 100 && local_flag == 1) {
        reorder_detected = 1;
        printf("检测到重排序!data=%d, flag=%d\n", local_data, local_flag);
    }
    
    return NULL;
}

int main() 
{
    pthread_t writer, reader;
    int i;
    int reorder_count = 0;
    int test_count = 10000;
    
    printf("开始测试 %d 次,使用原子操作防止重排序...\n", test_count);
    printf("使用 memory_order_release 和 memory_order_acquire 保证顺序\n\n");
    
    for (i = 0; i < test_count; i++) {
        // 重置变量
        atomic_store(&data, 0);
        atomic_store(&flag, 0);
        
        // 创建线程
        pthread_create(&writer, NULL, writer_thread, NULL);
        pthread_create(&reader, NULL, reader_thread, NULL);
        
        // 等待线程结束
        pthread_join(writer, NULL);
        pthread_join(reader, NULL);
        
        if (reorder_detected) {
            reorder_count++;
            reorder_detected = 0;
        }
        
        if ((i + 1) % 1000 == 0) {
            printf("已完成 %d 次测试,重排序次数:%d\n", i + 1, reorder_count);
        }
    }
    
    printf("\n测试结果:\n");
    printf("总测试次数:%d\n", test_count);
    printf("检测到重排序次数:%d\n", reorder_count);
    printf("重排序比例:%.2f%%\n", (float)reorder_count / test_count * 100);
    printf("\n结论:使用正确的内存顺序(acquire-release)可以完全防止重排序\n");
    
    return 0;
}

 

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