Title: Pthreads
1(No Transcript)
2Pthreads
- include ltpthread.hgt
- pthread_t tid //thread id.
- pthread_attr_t attr
- void sleeping(void ) / thread routine /
- main()
- int time 2
- pthread_create(tid, NULL, sleeping, time)
-
- void sleeping(int sleep_time)
- printf(thread sleeping for d secs\n,
sleep_time) -
-
3Pthreads
- Problem When main exits the process exits.
- main()
- int time 2
- pthread_create(tid, NULL, sleeping, time)
- pthread_join(tid, void NULL)
-
- void sleeping(int sleep_time)
- printf(thread sleeping for d secs\n,
sleep_time) -
-
4- pthread_t tids10
- main()
-
- for (j 0 j lt 10 j)
- pthread_create(tidsi, NULL, sleeping, time)
- for(j 0 j lt 10 j)
- pthread_join(tidi, NULL)
5All theads share global variables file
descriptors static variables within creating
function. Local variables are private to each
thread. void sleeping(int sleep_time)
static int tootoo 10 printf(thread
sleeping for d secs\n, sleep_time)
tootoo //will have final value of 20.
6Synchronization Constructs mutex and condition
variables Main() pthread_mutex_t my_mute
//initialize pthread_mutex_init(my_mute,
NULL) pthread_mutex_lock(my_mute)//blocks
caller till mutex unlocked // by owner
-critical code pthread_mutex_unlock(my_mute)
7You can also test a mutex to see if it is
available pthread_mutex_trylock(my_mute) If
multiple threads blocked on mutex, one will be
chosen Based on the scheduling algorithm.
8Condition variable allows threads to wait on some
event and resume when the event has
occurred. Condition variable associated with a
mutex! Thread must acquire mutex before calling
pthread_cond_wait(). pthread_mutex_t my_mute
pthread_cond_t condalisa pthread_mutex_init(m
ymute) thread_cond_init(condalisa)
9pthread_mutex_lock(my_mute) pthread_cond_wait(
condalisa, my_mute) This call to wait
atomically checks the condition and blocks (if
necessary). If the thread blocks, the mutex is
automatically released. Woken up with call to
pthread_cond_signal pthread_cond_signal(cond
alisa) //wakes up one //thread. pthread_co
nd_broadcast (condalisa) //wakes up all
threads