源代码:
vim 11_10.c
#include <stdlib.h>
#include <pthread.h>
struct foo{
pthread_mutex_t mutex;
int count;
int foo_id;
};
struct foo * initial(int id)
{
struct foo *fp;
if (fp = malloc(sizeof(struct foo)) != NULL){
fp->count = 1;
fp->foo_id = id;
if (pthread_mutex_init(&fp->mutex,1) == NULL){
free(fp);
return NULL;
}
return fp;
}
else
return NULL;
}
void foo_add(struct foo *fp)
{
pthread_mutex_lock(&fp->mutex);
fp->count++;
pthread_mutex_unlock(&fp->mutex);
}
void foo_del(struct foo *fp)
{
pthread_mutex_lock(&fp->mutex);
if (--fp->count == 0){
pthread_mutex_unlock(&fp->mutex);
pthread_mutex_destory(&fp->mutex);
free(fp);
}
else
pthread_mutex_unlock(&fp->mutex);
}
在count减少的时候,要判断为0的时候在destory free。保证没有别的线程在引用。