'Incrementing variable's value with multithreading
I tried to write a Code with 2 threads, which should increment the 2 numbers x y to 100, everytime an increment happens, it should be printed out.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *inc_x(void *x_void_ptr){
int *x_ptr = (int *)x_void_ptr;
while (++(*x_ptr)<100) {
printf("x increment to %d \n",*x_ptr);
*x_ptr++;
}
return NULL;
}
void *inc_y(void *y_void_ptr){
int *y_ptr = (int *)y_void_ptr;
while (++(*y_ptr)<100) {
printf("y increment to %d \n",*y_ptr);
*y_ptr++;
}
return NULL;
}
int main()
{
int x = 0;
int y = 0;
printf("x: 0 , y : 0\n");
pthread_t inc_x_thread, inc_y_thread;
if (pthread_create(&inc_x_thread, NULL, inc_x, &x)) {
fprintf(stderr, "Error creating thread \n");
return 1;
}
if (pthread_create(&inc_y_thread, NULL, inc_y, &y)) {
fprintf(stderr, "Error creating thread \n");
return 2;
}
printf("%d , %d" , x,y);
return 0;
}
but my x,y values were not incremented. Can someone tell me why ? Thanks (I am new to C by the way).
Solution 1:[1]
use following in main before checking reflected values of x and y:
pthread_join(inc_x_thread, NULL);
pthread_join(inc_y_thread, NULL);
and
use like this in both functions while incrementing : (*y_ptr)++;
void *inc_y(void *y_void_ptr){
int *y_ptr = (int *)y_void_ptr;
while (++(*y_ptr)<100) {
printf("y increment to %d \n",*y_ptr);
(*y_ptr)++; // correction here
}
return NULL;
}
Solution 2:[2]
You can try to use mutex, what will stop another thread until finish that task.
do something like that.
init mutex variable
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, NULL);
Then inside function
void *inc_x(void *x_void_ptr){
pthread_mutex_lock(&mutex);
//do something what will shared with another threads.
pthread_mutex_unlock(&mutex);
...
}
Then destroy mutex
pthread_mutex_destroy(&mutex);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Lee Taylor |
