




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





Jingke Li
Portland State University
Jingke Li (Portland State University) CS 415/515 Pthreads 1 / 15
The standard thread package on Unix systems. To use it, compile a program with -lpthread flag.
Jingke Li (Portland State University) CS 415/515 Pthreads 3 / 15
#include <pthread.h> void child(int ip) { printf("Child %d\n", ip); } main() { int i=1, j=2; pthread_t thread1, thread2; pthread_create(&thread1, NULL, (void) child, (void)&i); pthread_create(&thread2, NULL, (void) child, (void)&j); printf("Parent: waiting for child 1\n"); pthread_join(thread1, NULL); printf("Parent: waiting for child 2\n"); pthread_join(thread2, NULL); printf("Parent: done\n"); }
It will lock an unlocked mutex and return 0 or will return with EBUSY if the mutex is locked — useful in overcoming deadlock.
Jingke Li (Portland State University) CS 415/515 Pthreads 7 / 15
Condition variables are associated with a specific mutex.
Signals are not remembered, which means that threads must already be waiting for a signal to receive it.
Jingke Li (Portland State University) CS 415/515 Pthreads 9 / 15
Producer/consumer with bounded length.
void *producer(void *arg) { request_t *request; while(TRUE) { request = get_request(); pthread_mutex_lock(&req_lock); while (length >= 10) pthread_cond_wait(&req_producer, &req_lock); add_request(request); length++; pthread_mutex_unlock(&req_lock); pthread_cond_signal(&req_consumer); } }
void *slave(void ignored) { / Slave threads / int local_index, partial_sum = 0; do { pthread_mutex_lock(&mutex1); / get next idx into the array / local_index = global_index; / read current idx & save locally / global_index++; / increment global index */ pthread_mutex_unlock(&mutex1); if (local_index < array_size) partial_sum += *(a + local_index); } while (local_index < array_size);
pthread_mutex_lock(&mutex1); /* add partial sum to global sum / sum += partial_sum; pthread_mutex_unlock(&mutex1); return; / Thread exits */ }
Jingke Li (Portland State University) CS 415/515 Pthreads 13 / 15
void main() { int i; pthread_t thread[no_threads]; /* threads / pthread_mutex_init(&mutex1, NULL); / initialize mutex */
for (i=0; i<array_size; i++) /* initialize a[] / a[i] = i + 1; for (i=0; i<no_threads; i++) / create threads / if (pthread_create(&thread[i], NULL, slave, NULL) != 0) perror("Pthread_create fails"); for (i=0; i<no_threads; i++) / join threads */ if (pthread_join(thread[i], NULL) != 0) perror("Pthread_join fails"); printf("The sum of 1 to %i is %d\n", array_size, sum); }
Various attributes can be associated with threads, locks, and condition variables.