![]() |
![]() |
![]() |
Create thread
#include <pthread.h> int pthread_create( pthread_t* thread, const pthread_attr_t* attr, void* (*start_routine)(void* ), void* arg );
libc
The pthread_create() function creates a new thread, with the attributes specified in the thread attribute object attr. If attr is NULL, the default attributes are used (see pthread_attr_init()). If the attributes in attr are modified later, the thread's attributes aren't affected. Upon successful completion, pthread_create() stores the thread ID of the created thread in thread, if thread isn't NULL.
The thread is created executing start_routine() with arg as its only argument. If start_routine() returns, then there will be an implicit call to pthread_exit() using the return value of start_routine() as the exit status. The thread in which main() was invoked behaves differently. When it returns from main(), there's an implicit call to exit() using the return value of main() as the exit status.
The created thread inherits the signal mask of the parent thread, and its set of pending signals is empty.
![]() |
The pthread_join() or pthread_detach() functions must be called for threads created with a detachstate attribute of PTHREAD_CREATE_JOINABLE (the default) before all of the resources associated with the thread can be released at thread termination. |
![]() |
If the stacksize member of attr is set, the thread's actual stack size will be rounded up to a multiple of the system page size (which you can get by using the _SC_PAGESIZE constant in a call to sysconf()) if the system allocates the stack (the stackaddr member of attr is set to NULL). If the stack was previously allocated by the application, its size will not be changed. |
Create a thread in a detached state:
#include <stdio.h> #include <stdlib.h> #include <pthread.h> void* function( void* arg ) { printf( "This is thread %d\n", pthread_self() ); return( 0 ); } int main( void ) { pthread_attr_t attr; pthread_attr_init( &attr ); pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_DETACHED ); pthread_create( NULL, &attr, &function, NULL ); /* Allow threads to run for 60 seconds. */ sleep( 60 ); return EXIT_SUCCESS; }
Safety: | |
---|---|
Cancellation point | No |
Interrupt handler | No |
Signal handler | Yes |
Thread | Yes |
pthread_attr_init(), pthread_exit(), sysconf(), ThreadCreate()
![]() |
![]() |
![]() |