Thread creation/termination

Thread Creation

int pthread_create(&tid, &attr, func, &arg);
Thread destroy
  1. in a different thread
    • int pthread_cancel( tid );  // tid can be pthread_self()
      • the cancellation type and state of the target thread determine when the cancellation takes effect.
    • int pthread_join(tid, **value_ptr);
    • int pthread_abort(tid);  // tid can be pthread_self()
      • termination takes effect immediately (don’t wait for a cancellation point).
      • no cancellation handler called.
      • resources are not released (mutexes, file descriptors, etc)
  2. in the thread itself
    • void pthread_exit(*value_ptr);
      • value_ptr: thread’s exit status, which carries whatever you want the other thread (e.g. the thread calls pthread_join()) to know.
      • when the thread start routine returns, pthread_exit() is called implicitly.
    • void pthread_cleanup_push(cleanup_handler, &arg)
    • void pthread_cleanup_pop(execute)  // execute = 0, means the handler will not be executed.
      • the cleanup handler is pop/executed when the thread:
        • exits
        • acts on a cancellation request.
        • calls pthread_cleanup_pop() with nonzero.
      • NOTE! the cleanup handler should support multiple entrances.
#include <pthread.h>
struct my_context;
void *my_thread1(void *arg)
    struct my_context *cx=(struct my_context *)arg;
    return NULL; // pthread_exit() is called implicitly
void my_cleanup(void *args)
    struct my_context *ctx = (struct my_context *)args;
    if(ctx->iid != -1) {
void *my_thread2(void *arg)
    struct my_context *cx=(struct my_context *)arg;
    ctx->iid = InterruptAttachEvent(…);
    pthread_cleanup_push(my_cleanup, ctx);
    return NULL;
int main(int argc, char **argv)
    struct my_context *ctx;
    // create a thread with default attributes.  Don’t care about thread ID.
    // pthread_create(NULL, NULL, my_thread1, ctx);
    // create a thread with priority set to +20
    pthread_t tid;
    pthread_attr_t attr;
    struct sched_param param;
    int allowable_prio;
    pthread_getschedparam(pthread_self(), NULL, &param);
    allowable_prio = sched_get_priority_adjust(-1, SCHED_NOCHANGE, +20);
    param.sched_priority = allowable_prio;
    pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
    // pthread_attr_setschedpolicy(&attr, policy);  is this required?
    pthread_attr_setschedparam(&attr, &param);
    pthread_create(&tid, &attr, my_thread1, ctx); // all pointers
pthread_join(tid, NULL);  // wait/block until the target thread(tid) has terminated.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s