From 2c293e434b27df46f29946a0f8ce55f3ad2036a9 Mon Sep 17 00:00:00 2001 From: ichdream Date: Fri, 10 Sep 2021 15:22:43 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=AF=B9Linux=E5=B9=B3?= =?UTF-8?q?=E5=8F=B0=E5=A4=9A=E7=BA=BF=E7=A8=8B=E5=8D=95=E4=BE=8B=E6=A8=A1?= =?UTF-8?q?=E5=BC=8F=E8=B0=83=E7=94=A8=E7=9A=84=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 06.Singleton/2.Code/Singleton/Singleton.h | 2 +- 06.Singleton/2.Code/Singleton/main.cpp | 43 ++++++++++++++++++----- 2 files changed, 36 insertions(+), 9 deletions(-) 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