Reputation: 1795
I'm testing the behavior of running concurrent threads in C, with a thread function that runs infinitely. My question is why doesn't, in the below code, "HELLO!!!" gets printed? I thought pthread_create() is called and then immediately it goes to the next iteration of the loop, why is the code waiting for the 1st pthread_create() to finish? Aren't multiple threads supposed to be running concurrently?
void main(int argc, char **argv)
{
pthread_t tid;
int i;
//Create 4 inf threads
for (i=0;i< 4;i++)
{
//printf("hello!\n");
//pthread_create(&tid, NULL, thread_incr, (void *)i);
pthread_create(&tid, NULL, t_nostop, (void *)i);
printf("HELLO!!!"); //This linen is NEVER printed!!
}
pthread_exit(NULL);
}
void* t_nostop(void * argp)
{
int i=1;
int t_num=(int) argp;
while(i==1){t_num++;}
}
Upvotes: 0
Views: 5263
Reputation: 213
From my understanding on pthreads, you haven't actually started the thread yet. Try, after the pthread_create
, adding pthread_join(tid, NULL);
and see if it works.
Upvotes: 0
Reputation: 42175
Multiple threads are supposed to run concurrently. This should be happening in your code.
I'd guess that the printf
calls are executed but don't generate output immediately. Console output may be line buffered, so will only be displayed when you print a newline or flush.
Try either adding \n
at the end of the string you print or adding fflush(stdout)
after the printf
.
Edit: A comment asked about line buffering...
Line buffering happens when the standard C library decides that console writes are relatively expensive and should only be attempted for coherent blocks of text. One easy definition for a coherent block is a line. While it is waiting for a newline to be entered, the C lib stores the contents of printf
calls in a block of memory, appending subsequent printf
s
Upvotes: 6