Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1047781
  • 博文数量: 297
  • 博客积分: 11721
  • 博客等级: 上将
  • 技术积分: 3431
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-25 10:21
文章分类

全部博文(297)

文章存档

2016年(9)

2011年(71)

2010年(137)

2009年(80)

分类: C/C++

2009-11-16 19:03:44

#include
#include
#include
#include
#include

struct User * user;
void * thr_fn1(void *);
void * thr_fn2(void *);
struct User * user_alloc(void);
void user_hold(struct User * user,char *);
void user_rele(struct User * user);
static  struct User * fp;
struct User
{
        int f_count;
        pthread_mutex_t f_lock;
};
int main(int argc,char ** argv)
{
        pthread_t tid1,tid2;
        int err;
        void * tret;

        struct User * user;
        fp=user_alloc();
        sleep(2);
        pthread_create(&tid1,NULL,thr_fn1,NULL);

        pthread_create(&tid2,NULL,thr_fn2,NULL);
        pthread_join(tid1,&tret);
        pthread_join(tid2,&tret);

        user_rele(fp);
        return 0;
}

void * thr_fn1(void * arg)
{
        while(1)
        {
                sleep(1);
                user_hold(fp,"thread 1");
        }
        return ((void *)1);
}
void * thr_fn2(void * arg)
{
        while(1)
        {
                sleep(1);
                user_hold(fp,"thread 2");
        }
        pthread_exit((void *)2);
}
struct User * user_alloc(void)
{
        struct User * user;
        if((user=malloc(sizeof(struct User)))!=NULL)
                user->f_count=1;
        if((pthread_mutex_init(&user->f_lock,NULL))!=0)
        {
                free(user);
                return NULL;
        }
        printf("user_alloc complete.\n");
        return user;
}
void user_hold(struct User * user,char * thread)
{
        pthread_mutex_lock(&user->f_lock);
        user->f_count++;
        printf("from %s f_count = %d\n",thread,user->f_count);
        pthread_mutex_unlock(&user->f_lock);
}
void user_rele(struct User * user)
{
        pthread_mutex_lock(&user->f_lock);
        if(user->f_count==0)
        {
                pthread_mutex_unlock(&user->f_lock);
                pthread_mutex_destroy(&user->f_lock);
                free(user);
        }
        else
        {
                pthread_mutex_unlock(&user->f_lock);
        }
}
                                         
                                                       
阅读(778) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~