POSIX threads or pthreads
Notes
- I believe that these are the standard
- The pthread library is quite large and complex
- we will only do a basic pass.
- Everything needs to be linked with
-lpthread -
pthread_tis the equivalent ofpid_t - Threads are created with
pthread_create-
int pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr, typeof(void *(void *)) *start_routine, void *restrict arg); - thread is the new tid for the thread
- attr is a null or a list of thread attributes
- start_routine is a routine to call as the threads "main" function
-
static void * start_routine(void * arg)
-
- arg is a pointer to an argument
- For an int, float, double, ... it could just be the address of the pointer.
- Or even a nasty cast on each side.
- For more complex data, we will pass it in a struct.
-
- When the thread is created it will start executing the start_routine
- When it is finished, the thread should call
pthread_exitvoid pthread_exit(void * retval)
-
pthread_self()returns a tid_t- In my code I print this out.
- But I really should not, posix does not guarantee that this is a basic type (ie it could be a struct or class)
-
pthread_join-
int pthread_join(pthread_t thread, void **retval); - This is equivalent to
wait. - But retval contains the address of the return structures.
-
- Look at pi.cpp
- C++ has a thread library, built on top of pthreads
- The consturctor takes the starting process and all of theargs
- The .join method handles join
- The .joinable method returns if the thread is joinable.
- There are other methods, but these will do.
- There is much more, but this will do.