Click here to Skip to main content
14,303,059 members
Rate this:
Please Sign up or sign in to vote.
See more:
I dont understand the logic of this program . when I run the program
& gcc sample.c -pthread
& ./a.out


I cannot get the correct result. Sometimes I can see the result of
printf
func in thread and sometimes I cannot.What reason It can be?

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

void *thrFoo(void *arg){

	int x = *((int *)arg) ;

	printf("res : %d\n",x*5 );


}

int main()
{
	
	pthread_t thr;

	int a = 4 ;

	pthread_create(&thr,NULL,thrFoo,&a);


	printf("I am trying to understand the logic of\n");
	printf("Threads\n");


	return 0;
}
Posted
Comments
Richard MacCutchan 6-May-13 5:55am
   
It could be that your program is being terminated before the thread gets run. Try adding a Sleep() call in your main function after the thread is created.
Member 10031372 6-May-13 6:11am
   
thanks it worked.
Amir Mahfoozi 6-May-13 6:11am
   
Add a flag variable and set it to true at the end of your thread function.
In the main function set it to false and after creating the thread wait until the flag gets true.
Rate this:
Please Sign up or sign in to vote.

Solution 1

Because sometimes, your thread gets a chance to run before your application terminates, and sometimes it doesn't.

Think about it: You start a thread, print some lines and terminate your application. When you terminate, all thread associated with it are also terminated. So sometimes, there is space on a different core, and your thread runs immediately. Other times there isn't, and it gets queued. But then you app ends, so the thread is terminated before it gets a chance to do anything.

Try adding a read from the console before you exit the main function, or wait for the new thread to terminate first.
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

In addition to OriginalGriff's reply, see "Joining and Detaching Threads"[^].
   
Rate this:
Please Sign up or sign in to vote.

Solution 3

Main process should wait for thread to end
add
pthread_join(thr,NULL);
after thread.

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
 
void *thrFoo(void *arg){
 
	int x = *((int *)arg) ;
 
	printf("res : %d\n",x*5 );
 

}
 
int main()
{
	
	pthread_t thr;
 
	int a = 4 ;
 
	pthread_create(&thr,NULL,thrFoo,&a);
        pthread_join(thr,NULL); //Main Process should wait for thread to end
 

	printf("I am trying to understand the logic of\n");
	printf("Threads\n");
 

	return 0;
}
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100