pthread_key_create
函數(shù) pthread_key_create() 用來(lái)創(chuàng)建線程私有數(shù)據(jù)。該函數(shù)從 TSD 池中分配一項(xiàng),將其地址值賦給 key 供以后訪問使用。第 2 個(gè)參數(shù)是一個(gè)銷毀函數(shù),它是可選的,可以為 NULL,為 NULL 時(shí),則系統(tǒng)調(diào)用默認(rèn)的銷毀函數(shù)進(jìn)行相關(guān)的數(shù)據(jù)注銷。如果不為空,則在線程退出時(shí)(調(diào)用 pthread_exit() 函數(shù))時(shí)將以 key 鎖關(guān)聯(lián)的數(shù)據(jù)作為參數(shù)調(diào)用它,以釋放分配的緩沖區(qū),或是關(guān)閉文件流等。
不論哪個(gè)線程調(diào)用了 pthread_key_create(),所創(chuàng)建的 key 都是所有線程可以訪問的,但各個(gè)線程可以根據(jù)自己的需要往 key 中填入不同的值,相當(dāng)于提供了一個(gè)同名而不同值的全局變量(這個(gè)全局變量相對(duì)于擁有這個(gè)變量的線程來(lái)說)。
注銷一個(gè) TSD 使用 pthread_key_delete() 函數(shù)。該函數(shù)并不檢查當(dāng)前是否有線程正在使用該 TSD,也不會(huì)調(diào)用清理函數(shù)(destructor function),而只是將 TSD 釋放以供下一次調(diào)用 pthread_key_create() 使用。在 LinuxThread 中,它還會(huì)將與之相關(guān)的線程數(shù)據(jù)項(xiàng)設(shè)置為 NULL。
#include <stdio.h>
#include <stdlib.h>#include <pthread.h>
pthread_key_t ? key ;
struct ? test_struct ? {
???? int ? i ;
???? float ? k ;
};
void ? * child1 ?( void ? * arg )
{
???? struct ? test_struct ? struct_data ;
???? struct_data . i ? = ? 10 ;
???? struct_data . k ? = ? 3.1415 ;
???? pthread_setspecific ?( key , ? & struct_data );
???? printf ?( "結(jié)構(gòu)體struct_data的地址為 0x%p \n " , ? & ( struct_data ));
???? printf ?( "child1 中 pthread_getspecific(key)返回的指針為:0x%p \n " , ?( struct ? test_struct ? * ) pthread_getspecific ( key ));
???? printf ?( "利用 pthread_getspecific(key)打印 child1 線程中與key關(guān)聯(lián)的結(jié)構(gòu)體中成員值: \n struct_data.i:%d \n struct_data.k: %f \n " , ?(( struct ? test_struct ? * ) pthread_getspecific ?( key )) -> i , ?(( struct ? test_struct ? * ) pthread_getspecific ( key )) -> k );
???? printf ?( "------------------------------------------------------ \n " );
}
void ? * child2 ?( void ? * arg )
{
???? int ? temp ? = ? 20 ;
???? sleep ?( 2 );
???? printf ?( "child2 中變量 temp 的地址為 0x%p \n " , ?? & temp );
???? pthread_setspecific ?( key , ? & temp );
???? printf ?( "child2 中 pthread_getspecific(key)返回的指針為:0x%p \n " , ?( int ? * ) pthread_getspecific ( key ));
???? printf ?( "利用 pthread_getspecific(key)打印 child2 線程中與key關(guān)聯(lián)的整型變量temp 值:%d \n " , ? * (( int ? * ) pthread_getspecific ( key )));
}
int ? main ?( void )
{
???? pthread_t ? tid1 , ? tid2 ;
???? pthread_key_create ?( & key , ? NULL );
???? pthread_create ?( & tid1 , ? NULL , ?( void ? * ) child1 , ? NULL );
???? pthread_create ?( & tid2 , ? NULL , ?( void ? * ) child2 , ? NULL );
???? pthread_join ?( tid1 , ? NULL );
???? pthread_join ?( tid2 , ? NULL );
???? pthread_key_delete ?( key );
???? return ?( 0 );
}
總結(jié)
以上是生活随笔為你收集整理的pthread_key_create的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。