Reputation: 4390
I want to start a new thread from the main thread. I can't use join since I don't want to wait for the thread to exit and than resume execution.
Basically what I need is something like pthread_start(...), can't find it though.
Edit:
As all of the answers suggested create_thread should start thread the problem is that in the simple code below it doesn't work. The output of the program below is "main thread". It seems like the sub thread never executed. Any idea where I'm wrong?
compiled and run on Fedora 14 GCC version 4.5.1
void *thread_proc(void* x)
{
printf ("sub thread.\n");
pthread_exit(NULL);
}
int main()
{
pthread_t t1;
int res = pthread_create(&t1, NULL, thread_proc, NULL);
if (res)
{
printf ("error %d\n", res);
}
printf("main thread\n");
return 0;
}
Upvotes: 15
Views: 39414
Reputation: 1742
you need to call pthread_exit in the end of man(), which will cause main to wait other thread to start and exit. Or you can explicitly call pthread_join to wait the newly created thread
Otherwise, when main returns, the process is killed and all thread it create will be killed.
Upvotes: 1
Reputation: 3166
the behaviour of your code depends on the scheduler; probably the main program exits before printf in the created thread has been executed. I hope simple sleep(some_seconds) at the end of the main() will cause the thread output to appear :)
Upvotes: 9
Reputation: 23293
the join
call waits for the thread to terminate and exit.
if you want your main thread to continue its execution while the child thread is executing, don't call join
: the child thread will execute concurrently with the main thread...
Upvotes: 3
Reputation: 153909
The function to start the thread is pthread_create
, not
pthread_join
. You only use pthread_join
when you are ready to wait,
and resynchronize, and if you detach the thread, there's no need to use
it at all. You can also join from a different thread.
Before exiting (either by calling exit
or by returning from main
),
you have to ensure that no other thread is running. One way (but not
the only) to do this is by joining with all of the threads you've
created.
Upvotes: 22
Reputation: 43508
Just create the thread with the detached attribute set to on. To achieve this, you can either call pthread_detach
after the thread has been created or pthread_attr_setdetachstate
prior to its creation.
When a thread is detached, the parent thread does not have to wait for it and cannot fetch its return value.
Upvotes: 2
Reputation: 27632
Don't you just need to call pthread_create?
static void *thread_body(void *argument) { /* ... */ }
int main(void) {
pthread_t thread;
pthread_create(&thread, NULL, thread_body, NULL);
/* ... */
Upvotes: 0