Threads
Threads
main section
pthread_create() (create thread)
pthread_join() : wait for thread to
finish (optional : used if you want to
wait for the thread termination)
thread section
begins at function pointer
runs until pthread_exit()
Where,
thread is a variable that will hold the id of the thread.
retval is a double pointer (a pointer to a void pointer) that will be used to
store the exit status of the joined thread.
# On Windows :
winpty docker run -it --name Threads techtn/ubuntu :p2 bash
# On Mac or Linux :
docker run -it --name Threads techtn/ubuntu :p2 bash
If the container exits, use the following commands to re-run it and
retrieve your previous work :
# On Windows :
winpty docker attach Threads
# On Mac or Linux :
docker attach Threads
The option -pthread tells the gcc compiler that your program requires
threading support.
Dr. Abdeldjalil Labed Threads 14 / 20
Exiting a thread
The pthread_exit function terminates the calling thread and
returns a value
This function is usually written at the end of the starting routine.
If a value is returned by a thread upon ending, its reference is
passed as an argument.
Since a thread’s local variables (stack) are destroyed when it exits,
only references to global (data section) or dynamically allocated
variables (heap) are returned.
Where,
retval is a pointer to a return value
Note : If you want to pass more than one variable to the starting
routine use STRUCT
Dr. Abdeldjalil Labed Threads 17 / 20
Thread Issues
Consider the following function :