__thread
__thread
__thread修飾的變量,在每個線程中都有一份獨(dú)立實(shí)體,每個線程互不干擾,可以修飾全局性且值可能改變的變量
#include <iostream> #include <pthread.h> #include <unistd.h> using namespace std; // static __thread int i = 1; // 修飾static變量 __thread int i = 1; // 修飾全局變量void* work1(void* arg) {cout << ++i << endl; // 輸出2return NULL; }void* work2(void* arg) {sleep(1); // 等待線程work1修改i之后,繼續(xù)work2 cout << ++i << endl; // 輸出2return NULL; }int main() {pthread_t pid1, pid2;pthread_create(&pid1, NULL, work1, NULL);pthread_create(&pid2, NULL, work2, NULL);pthread_join(pid1, NULL);pthread_join(pid2, NULL);cout << i << endl; // 輸出1return 0; } 與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
- 上一篇: boost::function/bind
- 下一篇: muduo学习笔记 线程类