User-layer Thread API in POSIX

Thread Basics

Thread Creation

#include <pthread.h>
int
pthread_create(pthread_t *thread,
							 const pthread_attr_t *attr,
						   void *(*start_routine)(void*),
							 void *arg);
#include <stdio.h>
#include <pthread.h>

typedef struct {
    int a;
    int b;
} myarg_t;

void *mythread(void *arg) {
    myarg_t *args = (myarg_t *) arg;
    printf("%d %d\\n", args->a, args->b);
    return NULL;
}

int main(int argc, char *argv[]) {
    pthread_t p;
    myarg_T args = {10, 20};
    int rc = pthread_create(&p, NULL, mythread, &args);
    ...
}

User-layer Locks

int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
pthread_mutex_t lock;
int rc = pthread_mutex_init(&lock, NULL);
assert(rc == 0); // always check success!

pthread_mutex_lock(&lock);
x = x + 1; // or whatever your critical section is
pthread_mutex_unlock(&lock);

// check error code when calling lock
void Pthread_mutex_lock(pthread_mutex_t *mutex) {
		int rc = pthread_mutex_lock(mutex);
		assert(rc == 0);
}

User-layer Condition Variable

Sequence Coordination: threads need to wait for specific events or conditions

  1. wait for disk read to complete
  2. wait for pipe reader to make space in the pipe