2

I have this code:

#include<stdio.h> #include<string.h> #include<pthread.h> #include<stdlib.h> #include<unistd.h> int cont = 0; pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; void* codiceThreadIncremento(void *arg) { //sezione critica pthread_mutex_lock(&mut); printf("hello"); cont++; pthread_mutex_unlock(&mut); return NULL; } int main(void){ pthread_t thread1; pthread_t thread2; pthread_create(&thread1, NULL, &codiceThreadIncremento,NULL); printf("valore cont1 %d \n",cont); pthread_create(&thread2, NULL, &codiceThreadIncremento, NULL); printf("valore cont2 %d \n",cont); pthread_join(thread1,NULL); pthread_join(thread2,NULL); pthread_mutex_destroy(&mut); return 0; } 

I want try a simple increment of variable "cont" with the use of mutex.

When i execute this code I obtain this:

valore cont1 0 valore cont2 0 

But I expect

valore cont1= 1 valore con2 = 2 
2
  • Try printf("hello\n"); and move printf("valore cont2 %d \n",cont); after you join threads. Commented Dec 13, 2018 at 10:33
  • @AlexanderDmitriev GREAT!!! work! thanks :-) Commented Dec 13, 2018 at 10:51

2 Answers 2

4

I expect valore cont1= 1 valore con2 = 2"

You cannot expect anything from this program. You are accessing a variable in main while it's being modified in one or more threads. This is a data race and undefined behaviour.

Even if you add mutex protection in main, you cannot expect the increment to happen before you print the value. The whole point of threads is that they are executed asynchronously. If you want synchronous increments, don't use threads.

Sign up to request clarification or add additional context in comments.

Comments

1

The threads don't necessarily run until you call pthread_join.

By then you've already printed the output.

3 Comments

Are you sure? I think they'd run upon the pthread_create thread, but aren't guaranteed to be completed until after the pthread_join calls.
@Flau From the main thread's perspective, the child threads run any time between the call to pthread_create() that creates the thread is started to the time the call to pthread_join() that reaps the thread returns. A child thread might not even be scheduled much less run until the reaping pthread_join() call is made, and it might run to completion before the pthread_create() call that created it returns. Or anything in between.
@AndrewHenle Thanks, this is what I meant but articulated more accurately.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.