挥发性和多线程? [英] volatile and multithreading?

查看:126
本文介绍了挥发性和多线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下code:

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

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int ready = 0;

wait()
{
    int i;
    do
    {
        usleep(1000);
        pthead_mutex_lock(&mutex);
        i = ready;
        pthread_mutex_unlock(&mutex);
    } while (i == 0);   
    printf("Finished\n");
}

signal()
{
    pthead_mutex_lock(&mutex);
    ready = 1;
    pthread_mutex_unlock(&mutex);
}

我们产卵两个线程,我们调用wait在一个线程,然后调用另一个信号我们也让编译器优化大举

We spawn two threads we call wait in one thread and then call signal in the other We also get the compiler to optimize aggressively.

现在将在code像预期的那样还是会我们需要准备挥发性得到这个工作?将不同的编译器和库不同的方式处理这个?

Now will the code behave as expected or will we need to make ready volatile to get this to work? Will different compilers and libraries handle this differently?

编辑:我希望有可能是一个圆形的互斥功能,将prevent优化自身周围或编译器一般不全面优化的函数调用

I am hoping that there might be something round the mutex functions that will prevent optimization around itself or that the compiler generally does not optimize round function calls.

注意:我没有编译和测试code呢,会做,所以当我有机会

Note: I have not compiled and tested the code yet, will do so when I have a chance.

推荐答案

从内核君王一些观点:

http://kernel.org/doc/Documentation/volatile-considered- harmful.txt

这篇关于挥发性和多线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆