原来的main.cpp多线程执行的时候有bug,实际执行的是单线程

master
ichdream 2021-09-10 16:37:10 +08:00
parent e0c7e3db25
commit 0239628ce4
1 changed files with 30 additions and 14 deletions

View File

@ -51,18 +51,18 @@ int main()
} }
/* for linux platform */ /* for linux platform */
#else #else
#define THREAD_NUM 5 #define THREAD_NUM 6
#include<pthread.h> #include<pthread.h>
void* callSingleton_Lazy(void *pPM) void* callSingleton_Lazy(void*)
{ {
Singleton_Lazy *s = Singleton_Lazy::getInstance(); Singleton_Lazy *s = Singleton_Lazy::getInstance();
pthread_t nThreadNum = pthread_self(); pthread_t nThreadNum = pthread_self();
// sleep(50); // sleep(50);
printf("线程编号为%ld\n", nThreadNum); printf("线程编号为%lu\n", nThreadNum);
return 0; return 0;
} }
void* callSingleton_Hungry(void *pPM) void* callSingleton_Hungry(void*)
{ {
Singleton_Hungry *s = Singleton_Hungry::getInstance(); Singleton_Hungry *s = Singleton_Hungry::getInstance();
pthread_t nThreadNum = pthread_self(); pthread_t nThreadNum = pthread_self();
@ -74,21 +74,37 @@ void* callSingleton_Hungry(void *pPM)
int main() int main()
{ {
pthread_t threads_pool[THREAD_NUM]; pthread_t threads_pool[THREAD_NUM];
int tids[THREAD_NUM]; int tids[THREAD_NUM], i;
printf("Singleton Lazy mode:\n"); void* status;
for(int i = 0; i < THREAD_NUM; i++) pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i = 0; i < THREAD_NUM; i++)
{ {
tids[i] = pthread_create(&threads_pool[i], NULL, callSingleton_Lazy, NULL); if(i < THREAD_NUM / 2)
pthread_join(threads_pool[i], (void**)&tids[i]); tids[i] = pthread_create(&threads_pool[i], NULL, callSingleton_Lazy, (void*)&i);
else
tids[i] = pthread_create(&threads_pool[i], NULL, callSingleton_Hungry, (void*)&i);
if(tids[i])
{
printf("Error: unable to create thread.\n");
exit(-1);
}
} }
printf("Singleton Hungry mode:\n"); pthread_attr_destroy(&attr);
for(int i = 0; i < THREAD_NUM; i++) for(i = 0; i < THREAD_NUM; i++)
{ {
tids[i] = pthread_create(&threads_pool[i], NULL, callSingleton_Hungry, NULL); tids[i] = pthread_join(threads_pool[i], &status);
pthread_join(threads_pool[i], (void**)&tids[i]); if(tids[i])
{
printf("Error: unable to join.\n");
exit(-1);
}
} }
printf("main exiting.\n");
return 0; return 0;
} }