互斥锁使用范例

 
#define OBSERVER "Observer"

#include <pthread.h>
#include "log.h"
#include "observer.h"

static GList* observers;
static pthread_mutexattr_t mutexattr;//创建互斥锁
static pthread_mutex_t mutex;

void
observer_init()
{
       
        pthread_mutexattr_init(&mutexattr);
        pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);
        //设置属性
       
        pthread_mutex_init(&mutex, &mutexattr);//初始化互斥锁

        log_debug(OBSERVER, "Observer module is initialized.");
}

void
observer_exit()
{
        pthread_mutexattr_destroy(&mutexattr);
        pthread_mutex_destroy(&mutex);//注销互斥锁

        log_debug(OBSERVER, "Observer module exits.");
}

void
observer_register(OBSERVER_UPDATE update_func)
{
        pthread_mutex_lock(&mutex);//加锁
        observers = g_list_append(observers, update_func);
        pthread_mutex_unlock(&mutex);//解锁
}

void
observer_notify(int module, int event, void* userdata)
{
        int i;
        int len;
        OBSERVER_UPDATE update;

        pthread_mutex_lock(&mutex);

        len = g_list_length(observers);
        for (i = 0; i < len; i++) {
                update = (OBSERVER_UPDATE)g_list_nth_data(observers, i);
                if (update == NULL) {
                        continue;
                }

                update(module, event, userdata);
        }
        pthread_mutex_unlock(&mutex);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值