Title: Posix Threads
1Posix Threads
- Shared address systems
- Will become more of an issue as higher core
processors become more available. - POSIX Portable Operating System Interface
2Simple Example
- include ltpthread.hgt
- int err
- void main()
- pthread_t tidMAX
- for (i0 iltt i)
- errpthread_create(tidi,NULL,
count3s,i) - for (i0iltti)
- errpthread_join(tidi, (void )
statusi)
3Code Spec 6.1 pthread_create(). The POSIX
Threads thread creation function.
4Code Spec 6.2 pthread_join(). The POSIX Threads
rendezvous function.
5Code Spec 6.3 pthread_self(). The POSIX Threads
function to fetch a threads ID.
6Code Spec 6.4 pthread_equal(). The POSIX Threads
function to compare two thread IDs for equality.
7Code Spec 6.5 pthread_exit(). The POSIX Threads
thread termination function.
8Pthread Attributes
- Uses type pthread_attr_t
- Detached or Joinable
- Detached cannot be joined (less overhead)
- For us, rarely needed
- Bound or Unbound
- Bound threads are scheduled by OS (what we use
mostly) - Unbound scheduled by threads library
9Code Spec 6.6 pthread attributes. An example of
how thread attributes are set in the POSIX
Threads interface.
10Be Careful pass addresses, not values
- void main()
- pthread_t tid int status
- pthread_create(tid, NULL, start, NULL)
- pthread_join(tid, (void ) status)
- void start()
- int errorcode
- errorcodesomething
- pthread_exit(errorcode) ? problem here
11Code Spec 6.7 The POSIX Threads routines for
acquiring and releasing mutexes.
pthread_mutex_t lockPTHREAD_MUTEX_INITIALIZER
12Code Spec 6.8 The POSIX Threads routines for
dynamically creating and destroying mutexes.
13Code Spec 6.9 An example of how dynamically
allocated mutexes are used in the POSIX Threads
interface.
14Figure 6.1
15Code Spec 6.10 pthread_cond_wait(). The POSIX
Thread routines for waiting on condition
variables.
16Code Spec 6.11 pthread_cond_signal(). The POSIX
Threads routines for signaling a condition
variable.
17Figure 6.3 Bounded buffer example using
condition variables nonempty and nonfull.
18Figure 6.4 Example of why a signaling thread
needs to be protected by a mutex.
19Code Spec 6.12 The POSIX Threads routines for
dynamically creating and destroying condition
variables.
20Figure 6.6 Example of thread-specific data in
POSIX Threads. Thread-specific data are accessed
by keys, which map to different memory locations
in different threads.
21Code Spec 6.13 Example of how thread-specific
data is used. Once initialized with this code,
any procedure can access the value of my_index.
22Code Spec 6.14 pthread_key_create(). POSIX
Thread routine for creating a key for
thread-specific data.
23Code Spec 6.15 pthread_key_delete(). POSIX
Thread routine for deleting a key.
24Code Spec 6.16 pthread_setspecific(). POSIX
Thread routine for setting the value of
thread-specific data.
25Code Spec 6.17 pthread_getspecific(). POSIX
Thread routine for getting the value of some
thread-specific data.