Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
2.33/5 (2 votes)
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.

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.
 
Share this answer
 
In addition to OriginalGriff's reply, see "Joining and Detaching Threads"[^].
 
Share this answer
 
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;
}
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900