A thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system.

Using pthreads library in C
- In your C program you need to
#include <pthread.h>. - There are many functions related to pthreads.
- On a UNIX-based system, a list of these functions can typically be obtained with
man -k pthread. - To know about a specific function see the man page.
- When linking, you must link to the pthread library using compilation flag
-lpthread: gcc -lpthread file.c
Spawning a thread using pthread_create()
- A thread is created using
pthread_create()
int pthread_create(
pthread_t *thread_id, // ID number for thread
const pthread_attr_t *attr, // controls thread attributes
void *(*function)(void *), // function to be executed
void *arg // argument of function
);- Returns 0 if the thread creation is successful.
- Otherwise returns a non-zero value to indicate an error.
- We will use default attributes set by the system, so
*attrgets replaced byNULL, the easier syntax is :
int pthread_create(
pthread_t *thread_id, // ID number for thread
NULL, // we set it to default thread attributes
void *(*function)(void *), // function to be executed
void *arg // argument of function
);
Consider the function with multiple arguments
T *foo (T *, T*)where T represents any data type.
Solution : Pack arguments into a struct and create a wrapper, which takes the compound argument and unpacks before passing the unpacked arguments to foo()
typedef struct Compound {
T *a, *b;
} Compound_t;
T * foo_wrapper(Compound_t *c) {
// This can be passed to pthread_create
T *d;
d = foo(c->a, c->b);
}