Pthreads
Pthreads
Anandha Gopalan
November 24th 2017
What are Pthreads?
POSIX (Portable Operating System Interface) Threads
Implementation depends on the system
Implemented as a library on POSIX compliant Unix systems
→ libpthread
Since Kernel version 2.6, implemented in Linux as the Native
POSIX Thread Library ⇒ 1-1 relationship between threads
created and Kernel threads
Provides APIs for creating and managing threads
2/6
Creation
#include int pthread create (pthread t *thread, const pthread attr t *attr, pthread create (ID, Attributes, Function Pointer, Argument) ID → ID of newly created thread (set by the system) Attributes → Generally set to NULL for default attributes Function Pointer → Pointer to the function which will be Argument → Argument to the Function 3/6 Create and pass parameters (Example from CW) Pass address of producerid so that we get id of thread created back pthread_t producerid; int parameter = 5; pthread_create (&producerid, NULL, producer, (void *) ¶meter); Have to cast to correct data type in function void *producer (void *parameter) { int *param = (int *) parameter; cout << "Parameter = " << *param << endl;
pthread_exit(0);
}
4/6
Create and pass parameters
How do we create multiple threads?
Hint: Using an array to hold multiple thread IDs
How do we pass multiple parameters?
Can use global variables
Hint: Using structures ⇒ struct data type declaration and passing
the structure as a parameter is a more elegant solution
5/6
Exit
Exit from Thread
#include void pthread exit (void *retval) pthread exit (0); Wait for thread to finish and exit main programme #include int pthread join (pthread t thread, void **retval) pthread join (producerid, NULL); 6/6
void *(*start routine) (void *), void *arg)
executed by the newly created thread