Reputation: 21
I wrote this program to practice pthread system calls so I used some printing lines to check the results but they are escaped the output is:
Thread 1 created
Thread 2 created
test3
while I think it should be
thread 1 created
test2
thread 2 created
test3
test1
The order may change but I should have this lines so why it escape this print statements?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
void *function();
void *function2();
int main(int argc, char *argv[])
{
pthread_t tid;
int rc;
rc = pthread_create(&tid, NULL, function(), NULL);
if(rc > 0){
fprintf(stderr, "Error\n");
exit(1);
}
pthread_join(tid, NULL);
sleep(1);
printf("test1\n");
pthread_exit(NULL);
}
void *function(){
int rc;
pthread_t tid;
printf("Thread 1 created\n");
rc = pthread_create(&tid, NULL, function2(), NULL);
if(rc > 0){
fprintf(stderr, "Error\n");
exit(1);
}
printf("test2\n");
pthread_exit(NULL);
}
void *function2(){
pthread_detach(pthread_self());
printf("Thread 2 created\n");
printf("test3\n");
pthread_exit(NULL);
}
Upvotes: 0
Views: 307
Reputation: 52589
rc = pthread_create(&tid, NULL, function(), NULL);
You're trying to call pthread_create()
with the pointer returned by calling function()
as the function to run in the new thread (Remember, function arguments get evaluated before the function itself is called). Now, function()
doesn't actually return any value, but it calls function2()
in its body (while evaluating the arguments for another call to pthread_create()
), which also doesn't return any value, but does call pthread_exit()
instead. Since there's only one thread at that point because only the main process thread is running (pthread_create()
hasn't actually been called yet; the call stack looks like main() -> function() -> function2()
), the whole program then exits.
You need to call pthread_create()
with pointers to function
and function2
, not the results of calling them:
rc = pthread_create(&tid, NULL, function, NULL);
etc.
Upvotes: 3