Introduction

  • A new abstraction for a single running process.

  • Switch between threads

    • Each thread has it own program counter and set of registers

      • so, each thread has its own stack.
    • When switching from running thread (T1) to other (T2)

      1. Save the register state of T1
      2. Restore the register state of T2
      • The address space remains the same

Concurrency Problem

  • Problem Example:

    • Thread:

      • A function runs within the same memory space.
      • Each thread starts running in a routine call worker() (real program).
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      #include <stdio.h>
      #include <stdlib.h>
      #include <pthread.h>

      volatile int counter = 0;
      int loops;

      void *worker(void *arg) {
      int i;
      for (i = 0; i < loops; i++) {
      counter++;
      }
      return NULL;
      }

      int main(int argc, char *argv[])
      {
      if (argc != 2) {
      fprintf(stderr, "usage: threads <value>\n");
      exit(1);
      }

      loops = atoi(argv[1]);
      pthread_t p1, p2;
      printf("Initial value : %d\n", counter);

      pthread_create(&p1, NULL, worker, NULL);
      pthread_create(&p2, NULL, worker, NULL);
      pthread_join(p1, NULL);
      pthread_join(p2, NULL);
      printf("Final value : %d\n", counter);
      return 0;
      }
    • ./x 100

      • Initial value : 0
      • Final value : 200
    • ./x 10000000

      • Initial value : 0
      • Final value : 10096682
    • Since when we do increment, it takes 3 instructions:

      1. Load the value of counter from the memory to the register
      2. Increment it
      3. Store it back to the memory
      • But these 3 instructions do not execute atomically, so the problem of concurrency happened.
  • Solution:

    • Critical Section

      • A piece of code that accesses a shared variable, must not be concurrently executed by more than one thread.
        • So, multiple threads which execute the critical section should result in a race condition
        • Need to support atomicity for critical sections
    • Lock

      • To ensure that the critical section can execute only if it was a single automic instruction
        1
        2
        3
        4
        5
        6
        lock_t mutex;
        ...
        lock(&mutex);
        /* Critical Section */
        balance = balance + 1
        unlock(&mutex);

Thread API

Thread Creation

  • Used to create a thread

  • Syntax:

    1
    2
    3
    4
    5
    6
    int pthread_create(
    pthread_t* thread,
    const pthread_attr_t* attr,
    void* (*start_routine)(void*),
    void* arg
    );
    • thread: interact with this thread (id)
    • attr: to specify any attributes this thread might have
    • start_routine: the function this thread start running in
    • arg: the argument to be passed to the function
  • Example:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    #include <pthread.h>
    typedef struct __myarg_t {
    int a;
    int b;
    } myarg_t;

    void *mythread(void *arg) {
    myarg_t *m = (myarg_t *) arg;
    printf("%d %d\n", m->a, m->b);
    return NULL;
    }
    int main(int argc, char *argv[]) {
    pthread_t p;
    int rc;
    myarg_t args;
    args.a = 10;
    args.b = 20;
    rc = pthread_create(&p, NULL, mythread, &args);
    ...
    }

Thread Wait

  • Used to wait for a thread to complete

  • Syntax: int pthread_join(pthread_t thread, void **value_ptr);

    • thread: the thread that wait for
    • value_ptr: a pointer to the return value
  • Example:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    #include <stdio.h>
    #include <pthread.h>
    #include <assert.h>
    #include <stdlib.h>

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

    typedef struct __myret_t {
    int x;
    int y;
    } myret_t;

    void *mythread(void *arg) {
    myarg_t *m = (myarg_t *) arg;
    printf("%d %d\n", m->a, m->b);
    myret_t *r = malloc(sizeof(myret_t));
    r->x = 1;
    r->y = 2;
    return (void *) r;
    }

    int main(int argc, char *argv[]) {
    int rc;
    pthread_t p;
    myret_t *m;

    myarg_t args;
    args.a = 10;
    args.b = 20;
    pthread_create(&p, NULL, mythread, &args);
    pthread_join(p, (void **) &m); // this thread has been
    // waiting inside of the
    // pthread_join() routine.
    printf("returned %d %d\n", m->x, m->y);
    return 0;
    }

Lock

  • Provide mutual exclusion to a cirtical section

  • Interface:

    1
    2
    int pthread_mutex_lock(pthread_mutex_t *mutex);
    int pthread_mutex_unlock(pthread_mutex_t *mutex);
  • Usage:

    1
    2
    3
    4
    pthread_mutex_t lock;
    pthread_mutex_lock(&lock);
    /* Critical Section ... */
    pthread_mutex_unlock(&lock);
    • If there is no other thread holds the lock, then the thread will acquire the lock and enter the critical section.
    • If another thread holds the lock, then the thread will not return from the call until it has acquired the lock.
  • Check Errors:

    1
    2
    3
    4
    5
    6
    // First way
    pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

    // Second way
    int rc = pthread_mutex_init(&lock, NULL);
    assert(rc == 0); // always check success!
    1
    2
    3
    4
    void Pthread_mutex_lock(pthread_mutex_t *mutex) {
    int rc = pthread_mutex_lock(mutex);
    assert(rc == 0);
    }
  • Lock Acquistion

    1. Return failure if the lock is already held

      1
      int pthread_mutex_trylock(pthread_mutex_t *mutex);
    2. Return after a timeout or after acquiring the lock

      1
      int pthread_mutex_timelock(pthread_mutex_t *mutex, struct timespec *abs_timeout);

Lock

mutex

  • Used to provide mutual exclusion between threads
  • We may use different locks to protect different variables, to increase concurrency

Design Lock

  • Evaluating Locks

    1. Mutual Exclusion

      • it can prevent multiple threads from entering a critical section.
    2. Fairness

      • each thread gets a fair shot at acquiring the lock if the lock is free.
    3. Performance

      • the time overheads added by using the lock
  • Controlling Interrupts
    • Disable Interrupts for critical sections
      • the earliest solution to provide mutual exclusion
      • invented for single processor systems.
      • Problems:
        1. Do not work on multiprocessors
        2. Code that masks or unmasks interrupts be executed slowly by modern CPUs