乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      線程私有數(shù)據(jù)(TSD)

       mrjbydd 2012-09-14

      線程私有數(shù)據(jù)(TSD)

      線程中特有的線程存儲(chǔ), Thread Specific Data 。線程存儲(chǔ)有什么用了?他是什么意思了?大家都知道,在多線程程序中,所有線程共享程序中的變量?,F(xiàn)在有一全局變量,所有線程都可以使用它,改變它的值。 而如果每個(gè)線程希望能單獨(dú)擁有它,那么就需要使用線程存儲(chǔ)了。表面上看起來(lái)這是一個(gè)全局變量,所有線程都可以使用它,而它的值在每一個(gè)線程中又是單獨(dú)存儲(chǔ) 的。這就是線程存儲(chǔ)的意義。

      下面說(shuō)一下線程存儲(chǔ)的具體用法。

      l          創(chuàng)建一個(gè)類型為 pthread_key_t 類型的變量。

      l          調(diào)用 pthread_key_create() 來(lái)創(chuàng)建該變量。該函數(shù)有兩個(gè)參數(shù),第一個(gè)參數(shù)就是上面聲明的 pthread_key_t 變量,第二個(gè)參數(shù)是一個(gè)清理函數(shù),用來(lái)在線程釋放該線程存儲(chǔ)的時(shí)候被調(diào)用。該函數(shù)指針可以設(shè)成 NULL ,這樣系統(tǒng)將調(diào)用默認(rèn)的清理函數(shù)。

      l          當(dāng)線程中需要存儲(chǔ)特殊值的時(shí)候,可以調(diào)用 pthread_setspcific() 。該函數(shù)有兩個(gè)參數(shù),第一個(gè)為前面聲明的 pthread_key_t 變量,第二個(gè)為 void* 變量,這樣你可以存儲(chǔ)任何類型的值。

      l          如果需要取出所存儲(chǔ)的值,調(diào)用 pthread_getspecific() 。該函數(shù)的參數(shù)為前面提到的 pthread_key_t 變量,該函數(shù)返回 void * 類型的值。

      下面是前面提到的函數(shù)的原型:

      int pthread_setspecific(pthread_key_t key, const void *value);

      void *pthread_getspecific(pthread_key_t key);

      int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));

      下面是一個(gè)如何使用線程存儲(chǔ)的例子:

       

      復(fù)制代碼
      #include <stdio.h>
      #include <pthread.h>
      pthread_key_t   key;
      void echomsg(int t)
      {
              printf("destructor excuted in thread %d,param=%d\n",pthread_self(),t);
      }
      void * child1(void *arg)
      {
              int tid=pthread_self();
              printf("thread %d enter\n",tid);
              pthread_setspecific(key,(void *)tid);
              sleep(2);
              printf("thread %d returns %d\n",tid,pthread_getspecific(key));
              sleep(5);
      }
      void * child2(void *arg)
      {
              int tid=pthread_self();
              printf("thread %d enter\n",tid);
              pthread_setspecific(key,(void *)tid);
              sleep(1);
              printf("thread %d returns %d\n",tid,pthread_getspecific(key));
              sleep(5);
      }
      int main(void)
      {
              int tid1,tid2;
              printf("hello\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;
      }
      復(fù)制代碼

        本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評(píng)論

        發(fā)表

        請(qǐng)遵守用戶 評(píng)論公約

        類似文章 更多