互斥量(对数据结构保护)

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
/*
 * 当一个以上的线程需要访问动态分配的内存时,可以引入计数变量
 */
struct foo
{
    int f_count;
    pthread_mutex_t f_lock;
    int f_id;
};

struct foo* foo_alloc(int id)//allocate the object
{
    struct foo* fp;

    if((fp = (struct foo*)malloc(sizeof(struct foo))) != NULL)
    {
        fp->f_id = id;
        fp->f_count = 1;//引用计数加 1
        if(pthread_mutex_init(&fp->f_lock, NULL) != 0)
        {
            free(fp);
            return NULL;
        }
    }
    return fp;
}

/*
 * 功能:增加一个引用
 * 返回:无
 */
void foo_hold(struct foo *fp)
{
    pthread_mutex_lock(&fp->f_lock);
    fp->f_count++;
    pthread_mutex_unlock(&fp->f_lock);
}

/*
 * 功能:销毁结构体
 */
void foo_rele(struct foo *fp)
{
    //操作结构体之前锁住互斥量
    pthread_mutex_lock(&fp->f_lock);
    if(--fp->f_count == 0)//是最后的引用
    {
        pthread_mutex_unlock(&fp->f_lock);
        pthread_mutex_destroy(&fp->f_lock);
        free(fp);
    }
    else
        pthread_mutex_unlock(&fp->f_lock);
}

void printfoo(char *str, struct foo *fp)
{
    printf("%s", str);
    printf("f_count = %d\n", fp->f_count);
    printf("f_id = %d\n", fp->f_id);
}

/*
 * 功能:线程函数
 */
void* thread_func(void *arg)
{
    struct foo *fp = (struct foo*)arg;
    foo_hold(fp);
    fp->f_id = 2;
    foo_rele(fp);
    pthread_exit(NULL);
}
int main(void)
{
    int err;
    struct foo *fp;
    pthread_t thid;

    if((fp = foo_alloc(1)) == NULL)
    {
        printf("foo_alloc failed\n");
        exit(EXIT_FAILURE);
    }
    else
        printf("foo_alloc success\n");
    printfoo("main thread\n", fp);
    err = pthread_create(&thid, NULL, thread_func, (void*)fp);
    if(err != 0)
    {
        printf("thread_create failed\n");
        exit(EXIT_FAILURE);
    }

    err = pthread_join(thid, NULL);
    if(err != 0)
    {
        printf("pthread_join failed\n");
        exit(EXIT_FAILURE);
    }
    printfoo("after thread:\n", fp);
    foo_rele(fp);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值