pthread_key_create
生活随笔
收集整理的這篇文章主要介紹了
pthread_key_create
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
函數 pthread_key_create() 用來創建線程私有數據。該函數從 TSD 池中分配一項,將其地址值賦給 key 供以后訪問使用。第 2 個參數是一個銷毀函數,它是可選的,可以為 NULL,為 NULL 時,則系統調用默認的銷毀函數進行相關的數據注銷。如果不為空,則在線程退出時(調用 pthread_exit() 函數)時將以 key 鎖關聯的數據作為參數調用它,以釋放分配的緩沖區,或是關閉文件流等。
不論哪個線程調用了 pthread_key_create(),所創建的 key 都是所有線程可以訪問的,但各個線程可以根據自己的需要往 key 中填入不同的值,相當于提供了一個同名而不同值的全局變量(這個全局變量相對于擁有這個變量的線程來說)。
注銷一個 TSD 使用 pthread_key_delete() 函數。該函數并不檢查當前是否有線程正在使用該 TSD,也不會調用清理函數(destructor function),而只是將 TSD 釋放以供下一次調用 pthread_key_create() 使用。在 LinuxThread 中,它還會將與之相關的線程數據項設置為 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 ?( "結構體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關聯的結構體中成員值: \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關聯的整型變量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 );
}
總結
以上是生活随笔為你收集整理的pthread_key_create的全部內容,希望文章能夠幫你解決所遇到的問題。