1 분 소요

Thread API

  • Thread Creation
    • thread → a pointer to a structure of type pthread_t
    • attribute → to specify any attributes this thread might have
    • function pointer → a function name (start routine), which is passed a single argument of type void * (as indicated in the parentheses after start routine), and which returns a value of type void * (i.e., a void pointer).
    • arg → argument to be passed to the function where the thread begins execution

  • Thread completion
    • pthread_t is used to specify which thread to wait for.
    • a pointer to the return value you expect to get back
    • We can use NULL in the second argument to not care about the return value
    • In the case of passing a single value, we don’t have to package it up as an argument
    • we should note that one has to be extremely careful with how values are returned from a thread
      • never return a pointer which refers to something allocated on the thread’s call stack
    • procedure call
    • Long-lived programs may not need to join
  • Locks
    • POSIX threads library are those for providing mutual exclusion to a critical section via locks
      • int pthread_mutex_lock(pthread_mutex_t *mutex);
      • int pthread_mutex_unlock(pthread_mutex_t *mutex);
    • Only one thread is holding the lock, waiting for thbe lock acquisition
    • Lack of proper initialization
      • pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
      • int rc = pthread_mutex_init(&lock, NULL);
      • assert(rc == 0);
    • If your code doesn’t properly check error codes, the failure will happen silently, which in this case could allow multiple threads into a critical section.
  • Condition Variables
    • Condition variables are useful when some kind of signaling must take place between threads
    • int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
    • int pthread_cond_signal(pthread_cond_t *cond);
    • First, when signaling (as well as when modifying the global variable ready), we always make sure to have the lock held.
    • wait call takes a lock as its second parameter, to release the lock when putting caller to sleep
    • the waiting thread re-checks the condition in a while loop, instead of a simple if statement.
  • gcc -o main main.c -Wall -pthread

태그:

카테고리:

업데이트: