---
title: "多线程与volatile变量"
author: "kenby"
date: "2012-02-25T17:07:41Z"
tags: []
categories: ["互联网"]
slug: "volatile"
draft: false
lastmod: "2012-02-25T18:52:00Z"
id: 1423728
url: "https://kenby.iteye.com/blog/1423728"
---

volatile 修饰的变量表示改变量的值是易变的，编译器不对其进行优化，

访问该变量的时候不会从寄存器读取， 而是直接从内存读取变量。

在多线程环境下，每个线程都有一个独立的寄存器，用于保存当前执行的指令。

假设我们定义了一个全局变量，每个线程都会访问这个全局变量，这时候线程的

寄存器可能会存储全量变量的当前值用于后续的访问。当某个线程修改了全局变

量的值时，系统会立即更新该线程寄存器中对应的值，其他线程并不知道这个全局

变量已经修改，可能还是从寄存器中获取这个变量的值，这个时候就会存在不一致

的情况。

针对多线程访问共享变量而且变量还会经常变化的情况，利用volatile类型修饰变量

是一个很好的选择，如volatile int size = 10; 当多线程访问这个变量时，它会直接从

size对应的地址访问，而不会从线程对应的寄存器访问，这样就不会出现前面说到的

同一变量的值在多个线程之间不一致的情况。

下面贴出一个多线程环境下使用 volatile 变量的例子：

 

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

/* volatile变量控制线程的运行与结束 */
static volatile int do_run_thread = 1;  

static pthread_t thread_tid;

static void *work_thread(void *arg)
{
    while (do_run_thread) {
        printf("thread is running...\n");
        sleep(1);
    }
    printf("stop thread done!\n");
}

static void start_thread()
{
    printf("start thread...\n");
    pthread_create(&thread_tid, NULL, work_thread, NULL);
}

static void stop_thread()
{
    printf("stop thread...\n");
    do_run_thread = 0;
    pthread_join(thread_tid, NULL); /* 等待线程结束 */
}

int main()
{
    start_thread();
    sleep(5);
    stop_thread();

    return 0;
}
```