#include <pthread.h> #include <iostream> #include <mutex> using namespace std; std::once_flag g_flag; void once_func() { cout << __FUNCTION__ << "\t" << pthread_self() << " this is once call function!" << endl; }; void* one_func(void*) { cout << __FUNCTION__ << "\t" << "my thread id is " << pthread_self() << endl; std::call_once(g_flag, once_func); return NULL; }; void* two_func(void*) { cout << __FUNCTION__ << "\t" << "my thread id is " << pthread_self() << endl; std::call_once(g_flag, once_func); return NULL; }; int main() { pthread_t one,two,three; pthread_create(&one, NULL, one_func, NULL); usleep(1000); pthread_create(&two, NULL, two_func, NULL); usleep(1000); pthread_create(&three, NULL, one_func, NULL); usleep(1000); pthread_join(one, NULL); pthread_join(two, NULL); pthread_join(three, NULL); return 0; }
编译:g++ -g once_flag_test.cpp -std=c++0x -lpthread
gcc版本:gcc 版本 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)
因为用到了c++11的东东,所以在编译时需要加入-std=c++0x
对于once_flag和once_call实现的功能等同于linux中的pthread_once_t和pthread_call。
可以将代码中 pthread相关换成c++11中的thread类,这样就不存在平台问题了,不过windows平台上,可能需要vs2010或者vs2012。
运行结果:
one_func my thread id is 139888413087488
once_func 139888413087488 this is once call function!
two_func my thread id is 139888404694784
one_func my thread id is 139888396302080