test for thread local storage

Posted _BitterSweet

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了test for thread local storage相关的知识,希望对你有一定的参考价值。

#include <iostream>
#include <pthread.h>
#include <unistd.h>

using namespace std;
//__thread int iVar = 100;
int iVar = 100;
void* thread1(void *arg)

    iVar += 200;
    cout << "thread1 val : " << iVar << endl;


void* thread2(void *arg)

    iVar += 400;
    sleep(1);
    cout << "thread2 val : " << iVar << endl;


int main()

    pthread_t pid1, pid2;
    pthread_create(&pid1, NULL, thread1, NULL);
    pthread_create(&pid2, NULL, thread2, NULL);

    pthread_join(pid1, NULL);
    pthread_join(pid2, NULL);

    return 0;


  • 使用__thread int iVar = 100;的结果是

  • 只需要去操作拷贝的独立的副本,所以线程之间互不影响

  • 使用int iVar = 100;的结果是

以上是关于test for thread local storage的主要内容,如果未能解决你的问题,请参考以下文章