2016年7月15日 星期五

keyword: volatile 使用時機

主要有兩個功能: 如連結

其中一個是用在 thread 時,使用全域變數時,就需要使用
(感謝Bruce提供)
/* gcc -O3 volatile.c -o volatile -lpthread
without volatile
w1=35005211
w1=521595368
w2=35005211
================
with volatile
w1=1303455736
w1=35005211
w2=35005211
================
*/

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

//int  g_queue_idx = 0;
volatile int  g_queue_idx = 0;

void worker1(void *arg)
{
    while (1) {
        g_queue_idx = rand();
        printf("w1=%d\n", g_queue_idx);        
        sleep(1);
    }
}

void worker2(void *arg)
{
    int i, idx;
 
    while (1) {
        for (i = 0; i < 100000000; i++) {
      idx = g_queue_idx;   
        }

        printf("w2=%d\n", idx); 
        printf("================\n");
        sleep(2);
    }
}

int main(int argc, char **argv)
{
    pthread_t pid1, pid2;

    pthread_create(&pid1, NULL, (void *)&worker1, NULL);
    pthread_create(&pid2, NULL, (void *)&worker2, NULL);

    pthread_join(pid1, NULL);  
    pthread_join(pid2, NULL);  

    return 0;
}

沒有留言:

張貼留言