In Linux, multithreaded programming involves the use of threads, and the pthread library provides essential functions for creating, managing, and terminating threads. Threads enable concurrent execution, allowing for efficient utilization of system resources and enhanced program performance. The creation, deletion and management of threads are done by the functions present in the pthread library. Hereโs a list of few basic pthread library calls.
๐ฉ๐ญ๐ก๐ซ๐๐๐_๐๐ซ๐๐๐ญ๐() โ Used to create a new thread.
Synatax: int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
๐ฉ๐ญ๐ก๐ซ๐๐๐_๐๐ฑ๐ข๐ญ()- Called by a thread to exit and return a value to the calling thread.
Syntax: void pthread_exit(void *retval);
๐ฉ๐ญ๐ก๐ซ๐๐๐_๐ฌ๐๐ฅ๐()- Returns the thread ID of the calling thread. Used within a thread to obtain its own thread ID.
Syntax: pthread_t pthread_self(void);
๐ฉ๐ญ๐ก๐ซ๐๐๐_๐ฃ๐จ๐ข๐ง()- Used to wait for a thread to terminate. Blocks the subroutine until the thread specified in the call terminates.
Syntax: int pthread_join(pthread_t thread, void **retval);
๐ฉ๐ญ๐ก๐ซ๐๐๐_๐๐๐ญ๐๐๐ก() โ Detaches a thread and the resources allocated within a thread are released automatically when the thread exits.
Syntax:ย int pthread_detach(pthread_t thread);
๐ฉ๐ญ๐ก๐ซ๐๐๐_๐ฆ๐ฎ๐ญ๐๐ฑ_๐ข๐ง๐ข๐ญ() โ Initializes a mutex for thread synchronization.
Syntax: ย ย int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr);
๐ฉ๐ญ๐ก๐ซ๐๐๐_๐ฆ๐ฎ๐ญ๐๐ฑ_๐๐๐ฌ๐ญ๐ซ๐จ๐ฒ()- Destroys a mutex and releases the associated resources
Syntax: int pthread_mutex_destroy(pthread_mutex_t *mutex);
๐ฉ๐ญ๐ก๐ซ๐๐๐_๐ฆ๐ฎ๐ญ๐๐ฑ_๐ฅ๐จ๐๐ค() โ Locks a mutex, and makes other threads trying to lock it to block until the current thread releases the resource and makes it available.
Syntax: int pthread_mutex_lock(pthread_mutex_t *mutex);
๐ฉ๐ญ๐ก๐ซ๐๐๐_๐ฆ๐ฎ๐ญ๐๐ฑ_๐ญ๐ซ๐ฒ๐ฅ๐จ๐๐ค() โ Tries to lock a mutex but reurns immediately if the mutex is currently locked by another thread.
Syntax: int pthread_mutex_trylock(pthread_mutex_t *mutex);
๐ฉ๐ญ๐ก๐ซ๐๐๐_๐ฆ๐ฎ๐ญ๐๐ฑ_๐ฎ๐ง๐ฅ๐จ๐๐ค()- Unlocks the previously locked thread. The lock and unlock are used as wrapper functions.
Syntax: int pthread_mutex_unlock(pthread_mutex_t *mutex);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
An Article by: Yashwanth Naidu Tikkisetty
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~