💠 Different types of threads :
- User threads : also known as user-level threads or application threads , they are managed entierly by the application or user-level libraries , rather than the operating system’s kernel. these threads are created, scheduled and managed by the application itself without direct involvement from the OS.
» user threads provide level of abstraction and flexibility to the application.
» they are not visible to the OS ( handeled within the application’s address space).
» they do not take advantage of features like parallel execution on multiple processors.
» The threads you create using the language’s thread APIs (e.g., Java’s Thread class or Python’s threading module) are typically user threads.
- Kernel threads ( thread Noyau ) : also referred to as system threads or kernel-level threads, they are managed directly by the OS’s kernel , also supported and scheduled by the kernel. this allows them to take advantage of the parallel execution on multiple processors and utilize kernel-level ressources efficiently.
» they are Visible to the OS .
» The kernel manages the scheduling, synchronization, and resource allocation for these threads.
» they are typically created using system calls provided by the OS
( the threads created using system calls such as pthread_create
or CreateThread
are kernel threads. ) .
» These threads are scheduled and managed by the operating system kernel and can run in parallel on multiple processors.
💠Thread POSIX ( pthread.h
library ) :
🔸One of the key operations is creating a thread. To create a thread, we use the pthread_create
function, which has the following syntax:
int pthread_create (pthread_t *tid , const pthread_attr_t *tattr, void * (*start_routine)(void *), void *arg);
🔸Let’s break down the parameters of pthread_create
:
pthread_t *tid
: This is a pointer to a variable of typepthread_t
, which will hold the unique identifier of the created thread. This identifier can be used for further thread operations.const pthread_attr_t *tattr
: This parameter allows you to specify attributes for the thread, such as stack size or scheduling priority. You can passNULL
if you want to use the default attributes.void *(*start_routine)(void *)
: This is a function pointer to the routine that will be executed by the newly created thread. The routine should take avoid*
argument and return avoid*
value. This function will be the entry point of the thread.void *arg
: This is the argument that you can pass to thestart_routine
function. It can be any data or NULL if no argument is needed.
🔸 The pthread_create function returns an integer value. If the call is successful, it returns 0, indicating that the thread was created successfully. Otherwise, it returns a non-zero value, which represents an error identifier.
Here are some scenarios involving threads along with their corresponding code snippets in C using POSIX threads (pthread.h). These examples cover different use cases and thread-related operations: