日期:2014-05-16 浏览次数:20657 次
int gCount = 0;
class CCount
{
public:
CCount()
{
gCount++;
}
virtual ~CCount()
{
gCount--;
}
};
///////////////线程函数//////////
void* work_thread(void* arg)
{
CCount count;
.........
}
/**
* @file cntr.cpp
* @brief
*/
#include <iostream>
using namespace std;
#include <pthread.h>
int gCount = 0;
pthread_mutex_t gMutex = PTHREAD_MUTEX_INITIALIZER;
class CCount {
public:
CCount()
{
pthread_mutex_lock(&gMutex);
gCount++;
pthread_mutex_unlock(&gMutex);
}
~CCount()
{
pthread_mutex_lock(&gMutex);
gCount--;
pthread_mutex_unlock(&gMutex);
}
};
void *work_thread(void *arg)
{
CCount count;
return NULL;
}
#define N 1000
int main(int argc, char *argv[])
{
int i;
pthread_t tid[N];
for (i = 0; i < N; ++i) {
pthread_create(&tid[i], NULL, work_thread, NULL);
}
for (i = 0; i < N; ++i)
pthread_join(tid[i], NULL);
printf("gCount=%d\n", gCount);
return 0;
}