Threads
Threads
Threads
Sourangshu Bhattacharya
What are threads ?
• “Lightweight processes”
Process vs Thread
a single-threaded process = resource + execution
a multi-threaded process = resource + executions
Disadvantages:
★ Overhead: more information per thread needsto be stored.
Context switch is also slower.
★ Complexity: Kernel becomes more complex.Needs to handle
thread scheduling, etc.
Some functions:
Typical structure
main()
pthread_
create(func) func()
pthread_
join(id)
pthread_
exit()
Thread creation
Types: pthread_t – type of a thread
Some calls:
int pthread_create(pthread_t *thread,
const pthread_attr_t *attr,
void * (*start_routine)(void *),
void *arg);
int pthread_join(pthread_t thread, void **status);
int pthread_detach();
void pthread_exit();
Type: pthread_mutex_t
int pthread_mutex_init(pthread_mutex_t *mutex,
const pthread_mutexattr_t *attr);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
Type pthread_cond_t
int pthread_cond_init(pthread_cond_t *cond,
const pthread_condattr_t *attr);
int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_cond_wait(pthread_cond_t *cond,
pthread_mutex_t *mutex);
int pthread_cond_singal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);
Condition variables
• pthread_cond_init (condition,attr)
Initialize condition variable.
• pthread_cond_destroy (condition)
Destroy condition variable.
• pthread_cond_wait (condition,mutex)
Wait on condition variable.
• pthread_cond_signal (condition)
Wake up a random thread waiting on condition variable.
• pthread_cond_broadcast (condition)
Wake up all threads waiting on condition variable.
Pthread Sync Example
• This simple example code demonstrates the use of several Pthread condition
variable routines.
• The main routine creates three threads.
• Two of the threads perform work and update a "count" variable.
• The third thread waits until the count variable reaches a specified value
Pthread Sync Example
Pthread Sync Example
Pthread Sync Example