Programming Help

Joined
12/13/11
Messages
83
Points
18
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?

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 }
 
I would create two threads t1 and t2 using pthread_create with the same thread function. And see how is updated.
I have no hands-on experience with pthreads but the compiler might optimise var i to processor registers (normally use volatile vars).

Thus, no tid == stuff; just let t1 and t2 run to completion.

And 2 pthread_join!
 
Back
Top Bottom