Hi, i am writing this program to get myself started with posix thread.
I am expecting the program to output:
in main thread: i = 0
in child thread: i = 0 (maybe 1 here...the goal is to test shared variables in threads.)
However, the only output i see is
in main thread: i = 0
Why doesnt the child thread reach this if condition? if (pthread_equal(tid, mainThread) != 0)
How should i change the code to get the expected output?
I am expecting the program to output:
in main thread: i = 0
in child thread: i = 0 (maybe 1 here...the goal is to test shared variables in threads.)
However, the only output i see is
in main thread: i = 0
Why doesnt the child thread reach this if condition? if (pthread_equal(tid, mainThread) != 0)
How should i change the code to get the expected output?
Code:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <pthread.h>
4
5 void* thread(void* vargp);
6
7 int main(){
8 int i = 0;
9 pthread_t mainThread = pthread_self();
10 pthread_t tid;
11 pthread_create(&tid, NULL, thread, NULL);
12 if (pthread_equal(tid, mainThread) != 0){
13 printf("in child thread: i=%d\n", i);
14 i++;
15 }
16 if (pthread_equal(tid, mainThread) == 0){
17 printf("in main thread: i=%d\n", i);
18 i++;
19 }
20
21 pthread_join(tid, NULL);
22 exit(0);
23
24 }
25
26
27 void *thread(void* vargp){
28 //i++;
29 printf("Hello\n");
30 return NULL;
31 }