Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

c++ - volatile and multithreading?

In the following 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
");
}

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

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.

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?

Edit: 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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'd be surprised if the compiler assumes anything about a global variable in the presence of library function calls. That being said, volatile will not cost you anything, and it shows your intentions. I'd put it there.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...