Answer the question
In order to leave comments, you need to log in
Connoisseurs of C and mutex?
We have a code
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
int var = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond;
void * increment()
{
while(1)
{
pthread_mutex_lock(&lock);
++var;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
// sleep(1);
}
}
void * _print()
{
while(1)
{
pthread_mutex_lock(&lock);
pthread_cond_wait(&cond,&lock);
printf("%d\n", var);
pthread_mutex_unlock(&lock);
}
}
int main()
{
pthread_t th1, th2, th3;
pthread_create(&th1,NULL,increment, NULL);
pthread_create(&th2,NULL,_print,NULL);
pthread_join(th2,NULL);
pthread_join(th1,NULL);
return 0;
}
Answer the question
In order to leave comments, you need to log in
Well, there must be failures. ++ is much easier than a print, and in one unit of time it is performed much more often ... Cond can be removed, it seems to be superfluous here.
On the ancient process, everything goes synchronously, probably because the locking operations are much more complicated than ++ and print, which is why it switches contexts after each operation on the mutex ...
the mutexes in the example only ensure that var++ and print(var) are not executed in parallel, they do not provide order in any way in this example.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question