代码:
#include <iostream>
using namespace std;
#include <pthread.h>
#include <semaphore.h>
sem_t g_sem;
pthread_mutex_t g_mutex;
static int g_count = 0;
const int THREAD_NUM = 100;
void* ProcThread(void* arg)
{
int iNum = *(int*)arg;
sem_post(&g_sem);
pthread_mutex_lock(&g_mutex);
sleep(2);
g_count = g_count + 1;
cout << "child thread num = " << iNum << ", count = " << g_count << endl;
pthread_mutex_unlock(&g_mutex);
pthread_exit(NULL);
return NULL;
}
int main() {
sem_init(&g_sem, 0, 1);
pthread_mutex_init(&g_mutex, NULL);
pthread_t childThread[THREAD_NUM];
for (int i=0; i<THREAD_NUM; ++i)
{
sem_wait(&g_sem);
int iRet = pthread_create(childThread + i, NULL, ProcThread, &i);
if (iRet != 0)
{
cout << "error = " << iRet << endl;
}
}
for (int i=0; i<THREAD_NUM; ++i)
{
pthread_join(childThread[i], NULL);
}
sem_destroy(&g_sem);
pthread_mutex_destroy(&g_mutex);
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
return 0;
}
结果:
上面是用信号量系列函数来控制线程同步,如果换成互斥系列函数,结果也是一样,不能同步.
慕丝7291255