Thread-local storage  使用 一個變數, 每個 thread 看到這變數,像是 local 變數一般 !!!!

Linux gcc 宣告如下 :  static __thread  int x ;

以下是 sample :

struct data_
{
    int  id ;
    char name[16] ;
} ;
typedef struct data_ sdata ;

static __thread  sdata  tx ;

void *func1(void *arg)
{
    char *p = (char*) arg ;
    int pid  ;
    pid =  syscall( __NR_gettid );
    tx.id = pid ;
    strcpy(tx.name,p) ;
    while(1)
    {
        printf("(%d)(%s)\n",tx.id,tx.name) ;
        sleep(1) ;
    }
}

void *func2(void *arg)
{
    char *p = (char*) arg ;
    int pid  ;
    pid =  syscall( __NR_gettid );
    tx.id = pid ;
    strcpy(tx.name,p) ;
    while(1)
    {
        printf("(%d)(%s)\n",tx.id,tx.name) ;
        sleep(2) ;
    }
}

int main()
{
    pthread_t id[2];
    char p[2][16] ;
    strcpy(p[0],"Thread1") ;
    pthread_create(&id[0],NULL,func1,(void *)p[0]);
    strcpy(p[1],"Thread2") ;
    pthread_create(&id[1],NULL,func2,(void *)p[1] );


    int pid  ;
    pid =  syscall( __NR_gettid );
    tx.id = pid ;
    strcpy(tx.name,"MAIN") ;
    while(1)
    {
        printf("(%d)(%s)\n",tx.id,tx.name) ;
        sleep(5) ;
    }

}

The Answer :

(11384)(Thread1)
(11385)(Thread2)
(11384)(Thread1)
(11384)(Thread1)
(11385)(Thread2)
(11384)(Thread1)
(11384)(Thread1)
(11383)(MAIN)
(11385)(Thread2)
(11384)(Thread1)
(11384)(Thread1)
(11385)(Thread2)
(11384)(Thread1)
(11384)(Thread1)
(11385)(Thread2)
(11384)(Thread1)
(11383)(MAIN)

 

 

 

創作者介紹
創作者 hedgezzz 的頭像
hedgezzz

hedgezzz的部落格

hedgezzz 發表在 痞客邦 留言(0) 人氣()