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

在多线程环境中,全局变量的共享可能导致数据冲突。线程私有数据(TSD)允许每个线程拥有独立的数据结构。本文介绍了如何利用POSIX线程库创建和注销TSD,以实现线程安全的数据共享。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值