Threading
Library Required
1#include <pthread.h>
Types
pthread_create()
Creates a new thread and starts executing the specified routine in parallel
1int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);
Return Value:
- Success: 0
- Error: Error number
Example:
pthread_join()
Waits for the specified thread to terminate and optionally collects its return value
1int pthread_join(pthread_t thread, void **retval);
Return Value:
- Success: 0
- Error: Error number
Example:
pthread_detach()
Marks a thread as detached so its resources are automatically released on termination
1int pthread_detach(pthread_t thread);
Return Value:
- Success: 0
- Error: Error number
Example:
pthread_exit()
Terminates the calling thread and optionally returns a value to any joining thread
1void pthread_exit(void *retval);
Return Value:
- Does not return
Example:
pthread_self()
Returns the thread ID of the calling thread
1pthread_t pthread_self(void);
Return Value:
- The ID of the calling thread
Example:
pthread_attr_init()
Initializes a thread attribute object with default values
1int pthread_attr_init(pthread_attr_t *attr);
Return Value:
- Success: 0
- Error: Error number
Example:
pthread_attr_destroy()
Destroys a thread attribute object and frees associated resources
1int pthread_attr_destroy(pthread_attr_t *attr);
Return Value:
- Success: 0
- Error: Error number
Example:
Thread Attr Setter/Getter
These functions are used to set and get properties of a pthread_attr_t
object before creating a thread.
pthread_attr_setdetachstate / pthread_attr_getdetachstate
Sets or gets the detach state (joinable or detached).
Values: PTHREAD_CREATE_JOINABLE
(default) · PTHREAD_CREATE_DETACHED
Example
pthread_attr_setschedpolicy / pthread_attr_getschedpolicy
Sets or gets the scheduling policy.
Policies: SCHED_OTHER
(default) · SCHED_FIFO
· SCHED_RR
Example
pthread_attr_setschedparam / pthread_attr_getschedparam
Sets or gets scheduling parameters (e.g., priority).
Example
pthread_attr_setinheritsched / pthread_attr_getinheritsched
Sets or gets whether the thread inherits or explicitly uses scheduling attributes.
Values: PTHREAD_INHERIT_SCHED
· PTHREAD_EXPLICIT_SCHED
Example
pthread_attr_setstacksize / pthread_attr_getstacksize
Sets or gets the thread stack size.
Example
pthread_attr_setstack / pthread_attr_getstack
Sets or gets both stack address and size.
Example