Help! Posix Thread

Dec 22, 2012 at 9:44pm UTC
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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* thread(void* vargp);
int main(){
 int i = 0;
 pthread_t mainThread = pthread_self();
 pthread_t tid;
 pthread_create(&tid, NULL, thread, NULL);
 if (pthread_equal(tid, mainThread) != 0){
 printf("in child thread: i=%d\n", i);
 i++;
 }
 if (pthread_equal(tid, mainThread) == 0){
 printf("in main thread: i=%d\n", i);
 i++;
 }
 pthread_join(tid, NULL);
 exit(0);
}
void *thread(void* vargp){
 //i++;
 printf("Hello\n");
 return NULL;
}
Dec 23, 2012 at 12:22am UTC
Why doesnt the child thread reach this if condition? if (pthread_equal(tid, mainThread) != 0)
Why should it? The main thread just runs function thread then terminates.
Dec 27, 2012 at 3:18pm UTC
pthread_create is not process fork.
Dec 29, 2012 at 6:08am UTC
The statement if (pthread_equal(tid, mainThread) != 0) never runs true anyway, You're checking to see if tid is equal to mainThread, but tid is a thread handle of your *thread function not the main thread, so it will never not be equal to 0 because pthread_equal(tid, mainThread) will always return false. That's why it does print in main thread: i = 0. You could change it so that the *thread function itself prints the value of i and make i's scope global; BUT that isn't thread safe and to make it thread safe you're going to have to use mutex's.
Last edited on Dec 29, 2012 at 6:14am UTC
Dec 29, 2012 at 6:28am UTC
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* thread(void* vargp);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
 int i = 0;
int main(){
 pthread_t tid;
 pthread_create(&tid, NULL, thread, NULL);
		pthread_mutex_lock(&mutex);		
			i++;
		pthread_mutex_unlock(&mutex);
 printf("in main thread: i=%d\n", i);
 pthread_join(tid, NULL);
 exit(0);
}
void *thread(void* vargp){
 pthread_mutex_lock(&mutex);		
		i++;
	pthread_mutex_unlock(&mutex);
 printf("In Child thread i=%d\n",i);
 return NULL;
}

This should be thread safe and achieve what I think you were going for.
Last edited on Jan 23, 2013 at 3:57pm UTC
Topic archived. No new replies allowed.

AltStyle によって変換されたページ (->オリジナル) /