I'm having a simple question, I believe, as far as I know, a multithreaded program, they share the process's memory space between all threads, that includes, stack, global memory area, file descriptors, etc., I I want to know why in the first example, there is a consistency problem, since theoretically all threads share the stack, in the second example, the race problem occurs.
#include <stdio.h>
#include <pthread.h>
void *thr(void *arg)
{
for(int i = 0; i < 50; i++)
printf("Thread = %zu Value= %d\n", pthread_self(), i);
return NULL;
}
int main(void)
{
pthread_t threads[2];
for(int i = 0; i < 2; i++)
pthread_create(&threads[i], NULL, thr, NULL);
for(int i = 0; i < 2; i++)
pthread_join(threads[i], NULL);
return 0;
}
Second program with running problem
#include <stdio.h>
#include <pthread.h>
int i = 0;
void *thr(void *arg)
{
for(; i < 50; i++)
printf("Thread = %zu Value= %d\n", pthread_self(), i);
return NULL;
}
int main(void)
{
pthread_t threads[2];
for(int i = 0; i < 2; i++)
pthread_create(&threads[i], NULL, thr, NULL);
for(int i = 0; i < 2; i++)
pthread_join(threads[i], NULL);
return 0;
}
3 example with race problem, in this case the variable is created in the main thread and is passed as argument to the function, that is, the only shared stack is from the main thread ?
#include <stdio.h>
#include <pthread.h>
void *thr(void *arg)
{
int *ptr = (int *)arg;
for(; *ptr < 50; (*ptr)++)
printf("Thread = %zu Value= %d\n", pthread_self(), *ptr);
return NULL;
}
int main(void)
{
int i = 0;
pthread_t threads[2];
for(int i = 0; i < 2; i++)
pthread_create(&threads[i], NULL, thr, &i);
for(int i = 0; i < 2; i++)
pthread_join(threads[i], NULL);
return 0;
}