/**
* Author: ACb0y
* FileName: main.cpp
* CreateTime: 2011-10-12 23:19:34
* Version: 1.0
*/
#include <iostream>
#include <pthread.h>
#include "apue.h"
#include "err_msg.h"
using namespace std;
struct ChildThreadInfo
{
int cnt;
pthread_mutex_t lock;
};
ChildThreadInfo childThreadInfo;
void * ThreadRun(void *arg)
{
int id = *((int *)arg);
int count = 0;
pthread_mutex_lock(&childThreadInfo.lock);
childThreadInfo.cnt++;
pthread_mutex_unlock(&childThreadInfo.lock);
while (count != 3)
{
sleep(1);
count++;
cout << "Thread " << id << " run " << count << " second" << endl;
}
pthread_mutex_lock(&childThreadInfo.lock);
childThreadInfo.cnt--;
pthread_mutex_unlock(&childThreadInfo.lock);
}
int main()
{
pthread_t tid;
int id = 0;
while (true)
{
if (id < 3)
{
++id;
pthread_create(&tid, NULL, ThreadRun, (void *)&id);
}
sleep(1);
pthread_mutex_lock(&childThreadInfo.lock);
cout << "child thread count = " << childThreadInfo.cnt << endl;
pthread_mutex_unlock(&childThreadInfo.lock);
if (childThreadInfo.cnt == 0)
{
break;
}
}
cout << "all child threads stop and exit" << endl;
return 0;
}
* Author: ACb0y
* FileName: main.cpp
* CreateTime: 2011-10-12 23:19:34
* Version: 1.0
*/
#include <iostream>
#include <pthread.h>
#include "apue.h"
#include "err_msg.h"
using namespace std;
struct ChildThreadInfo
{
int cnt;
pthread_mutex_t lock;
};
ChildThreadInfo childThreadInfo;
void * ThreadRun(void *arg)
{
int id = *((int *)arg);
int count = 0;
pthread_mutex_lock(&childThreadInfo.lock);
childThreadInfo.cnt++;
pthread_mutex_unlock(&childThreadInfo.lock);
while (count != 3)
{
sleep(1);
count++;
cout << "Thread " << id << " run " << count << " second" << endl;
}
pthread_mutex_lock(&childThreadInfo.lock);
childThreadInfo.cnt--;
pthread_mutex_unlock(&childThreadInfo.lock);
}
int main()
{
pthread_t tid;
int id = 0;
while (true)
{
if (id < 3)
{
++id;
pthread_create(&tid, NULL, ThreadRun, (void *)&id);
}
sleep(1);
pthread_mutex_lock(&childThreadInfo.lock);
cout << "child thread count = " << childThreadInfo.cnt << endl;
pthread_mutex_unlock(&childThreadInfo.lock);
if (childThreadInfo.cnt == 0)
{
break;
}
}
cout << "all child threads stop and exit" << endl;
return 0;
}