Reputation: 247
I'm searching a way to lock a variable in a C program. The fact is this variable is set in loop by a thread but in the other hand I have in my main an infinite loop who's reading this variable.
Is there anyway to perform this?
Upvotes: 1
Views: 4600
Reputation: 16379
Consider a mutex:
volatile int var=0;
pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER;
to read the variable:
pthread_mutex_lock(&mtx);
local_var=var;
pthread_mutex_unlock(&mtx);
to set the variable:
pthread_mutex_lock(&mtx);
var=19;
pthread_mutex_unlock(&mtx);
This would be what is needed if you are writing a threaded application - you have a pthreads tag.
Upvotes: 2