#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;
的结果是