diff --git a/06.Singleton/2.Code/Singleton/Singleton.h b/06.Singleton/2.Code/Singleton/Singleton.h index 3ff8a6a..ca8d9a6 100644 --- a/06.Singleton/2.Code/Singleton/Singleton.h +++ b/06.Singleton/2.Code/Singleton/Singleton.h @@ -13,7 +13,7 @@ public: if (instance == NULL){ m_mutex.lock(); if (instance == NULL){ - printf("创建新的实例\n"); + printf("鍒涘缓鏂扮殑瀹炰緥\n"); instance = new Singleton(); } m_mutex.unlock(); diff --git a/06.Singleton/2.Code/Singleton/main.cpp b/06.Singleton/2.Code/Singleton/main.cpp index bee839c..823a31b 100644 --- a/06.Singleton/2.Code/Singleton/main.cpp +++ b/06.Singleton/2.Code/Singleton/main.cpp @@ -1,7 +1,7 @@ #include #include "Singleton.h" -/*单例模式简单实现*/ +/*鍗曚緥妯″紡绠鍗曞疄鐜*/ /* int main() { @@ -13,11 +13,12 @@ int main() } */ -/*非线程安全 单例模式*/ +#ifdef win32 +/*闈炵嚎绋嬪畨鍏 鍗曚緥妯″紡*/ #include #include -//多线程,线程数目:5 +//澶氱嚎绋嬶紝绾跨▼鏁扮洰锛5 #define THREAD_NUM 5 unsigned int __stdcall CallSingleton(void *pPM) @@ -25,7 +26,7 @@ unsigned int __stdcall CallSingleton(void *pPM) Singleton *s = Singleton::getInstance(); int nThreadNum = *(int *)pPM; Sleep(50); - //printf("线程编号为%d\n", nThreadNum); + //printf("绾跨▼缂栧彿涓%d\n", nThreadNum); return 0; } @@ -34,17 +35,43 @@ int main() { HANDLE handle[THREAD_NUM]; - //线程编号 + //绾跨▼缂栧彿 int threadNum = 0; while (threadNum < THREAD_NUM) { handle[threadNum] = (HANDLE)_beginthreadex(NULL, 0, CallSingleton, &threadNum, 0, NULL); - //等子线程接收到参数时主线程可能改变了这个i的值 + //绛夊瓙绾跨▼鎺ユ敹鍒板弬鏁版椂涓荤嚎绋嬪彲鑳芥敼鍙樹簡杩欎釜i鐨勫 threadNum++; } - //保证子线程已全部运行结束 + //淇濊瘉瀛愮嚎绋嬪凡鍏ㄩ儴杩愯缁撴潫 WaitForMultipleObjects(THREAD_NUM, handle, TRUE, INFINITE); system("pause"); return 0; -} \ No newline at end of file +} +/* for linux platform */ +#else +#define THREAD_NUM 5 +#include +void* callSingleton(void *pPM) +{ + Singleton *s = Singleton::getInstance(); + pthread_t nThreadNum = pthread_self(); + // sleep(50); + printf("绾跨▼缂栧彿涓%ld\n", nThreadNum); + return 0; +} + +int main() +{ + pthread_t threads_pool[THREAD_NUM]; + int tids[THREAD_NUM]; + for(int i = 0; i < THREAD_NUM; i++) + { + tids[i] = pthread_create(&threads_pool[i], NULL, callSingleton, NULL); + pthread_join(threads_pool[i], (void**)&tids[i]); + } + return 0; +} + +#endif \ No newline at end of file