Friday, January 31, 2014

pthread - Local data

pthread_once():

This is like constructor function.

int pthread_once( pthread_once_t * once_control, void (*init_routine)(void));

  • pthread_once_t:control variable. Needs to be initialized with PTHREAD_ONCE_INIT.
  • init_routine:Initialization function which will be called only once. This function even called from multiple threads, init_routine will be executed only once. And, the functions whoever calling this function will block untill the execution is completed.

    And only the global data can be accessed in the init_routine function.

    a. Stack
    b. Thread ID
    c. Signal mask
    d. Alternative signal stack
    e. errno variable
    f. scheduling policy and priority.

    Let's see functions which will make sure completely private area for the thread.
    • int pthread_key_create( pthread_key_t * key, void ( *destr_function )( void * ));
    Initialized the thread specific data key.
    key - thread specific data key. By this key, the thread specific data is accessed. It is necessary to execute pthread_key_create only once. Usually, pthread_once is used.
    destr_function - Destructor. if not used, assign NULL.
    • int pthread_key_delete( pthread_key_t key );
                Deletes thread specific key.
    • int pthread_setspecific( pthread_key_t key, const void * pointer );
                pointer value is associated with thread specific data key. Thread sepcific data is assigned to pointer.
    • void * pthread_getspecific( pthread_key_t key );
                Acquires the value managed by thread specific data key. If it is NULL, it needs to be set by pthread_setspcific();

    Though the variable is declared as global, it can be assigned data from multiple data and the data will be distinct for each thread. There are two ways:

    1)  declare using __thread
    __thread tsd_t * value = 0;
    2) The data needs to be declared as pthread_key_t and use pthread_key_create(& tsd_key, 0)
        pthread_key_t   tsd_key;
    Set and access using pthread_setspecific and pthread_getspecific.

    Destructor:

    Destructor will be executed when thread ends and it will have the data key as parameter. Allocated memory can be released. But, key itself can be deleted when the final destructor of the thread is called.

    After desctructor, pthread_join is called.

    TLS is simple and easy, just __thread prefix in the declaration.

    These can be used when porting multiprocessed application to multithreaded to declare static and extern.
     
  • No comments: