linux 多线程编程 Thread Specific Data (TSD)

在单线程程序中,我们经常使用 “全局变量” 以实现多个函数间共享数据,在多线程环境下,由于数据空间是共享的,因此全局变量也为所有线程所共享。但有时应用程序设计中有必要提供线程私有的全局变量,仅在某个线程中有效,但却可以跨多个函数访问,比如程序可能需要每个线程维护一个链表,而使用相同的函数操作,最简单的方法就是使用同名而不同变量地址的线程相关数据结构。这样的数据结构可以由POSIX线程库维护,称为线程私有数据(Thread-Specific Data, TSD)


下面两个API分别用来创建和注销TSD

int pthread_key_create(pthread_key_t* key, void (*destr_function)(void *))

int pthread_key_delete(pthread_key_t key)

下面这段代码是TSD的简单演示

#include
#include
#include

pthread_key_t key;

void echomsg( void* param )
{
        printf( "destructor excuted in thread %lu, param = %lu\n", pthread_self(), *((unsigned long int*)param) );
}

void* child1( void* param )
{
        unsigned long int  tid = pthread_self();
        printf( "thread %lu enter\n", tid );
        pthread_setspecific( key, ( void* )tid );

        sleep( 2 );
        unsigned long int  val = *((unsigned long int *)pthread_getspecific( key ));
        printf( "thread %lu returns %lu\n", tid, val );

        sleep( 5 );

        return ( void* )0;
}


void* child2( void* param )
{
        unsigned long int tid = pthread_self();
        printf( "thread %lu enter\n", tid );
        pthread_setspecific( key, ( void* )tid );

        sleep( 1 );
        unsigned long int  val = *( (unsigned long int*)pthread_getspecific( key ) );
        printf( "thread %lu returns %lu\n", tid, val );

        sleep( 5 );

        return ( void* )0;
}

int main()
{
        pthread_t tid1, tid2;
        printf( "main thread enter\n" );

        pthread_key_create( &key, echomsg );
        pthread_create( &tid1, NULL, child1, NULL );
        pthread_create( &tid2, NULL, child2, NULL );

        sleep( 10 );
        pthread_key_delete( key );

        printf( "main thread exit\n" );

        return 0;
}

// 编译要加 -lpthread

 g++ -lpthread -o TSD.out TSD.cpp


// main output

kennie@cbib:~/pthreadDIR$ ./TSD.out
main thread enter
thread 3075607408 enter
thread 3067214704 enter
thread 3067214704 returns 3067214704
thread 3075607408 returns 3075607408
destructor excuted in thread 3067214704, param = 3067214704
destructor excuted in thread 3075607408, param = 3075607408
main thread exit



你可能感兴趣的:(linux,多线程编程,Thread,Specific,Data,(TSD))