嵌入式 多线程socket互斥锁和条件变量实现广播包

互斥锁和条件变量出自Posix.1 线程标准,它们总是可用来同步一个进程内的各个线程。
如果一个互斥锁或条件变量存放在多个进程间共享的某个内存区中,那么Posix还允许它用于
这些进程间的同步。

互斥锁
mutual exclusion
critical region

Posix互斥锁作为数据类型pthread_mutex_t的变量声明。
如果互斥锁变量是静态分配的,那么我们可以把它初始化成常量PTHREAD_MUTEX_INITIALIZER:
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
如果互斥锁是动态分配的,或者分配在共享内存区中,必须在运行时刻通过调
用pthread_mutex_init函数初始化它。

int pthread_mutex_lock(pthread_mutex_t *mptr);
int pthread_mutex_trylock(pthread_mutex_t *mptr);
int pthread_mutex_unlock(pthread_mutex_t *mptr);
都返回:成功时为0,出错时为正的Exxx值。

编程技巧: 努力把共享数据和他们的同步变量(互斥锁,条件变量活信号灯)收集到一个结构中。

条件变量:
int pthread_cond_wait(pthread_cond_t *cptr, pthread_mutex_t*mpthr);
int pthread_cond_signal(pthread_cond_t cptr);
都返回: 成功时为0,出错时为正的Exxx值

pthread_cond_wait 函数原子地执行以下两个动作:
1. 给互斥锁解锁
2. 把调用线程投入睡眠,直到另外某个线程就本条件变量调用pthread_cond_signal.

pthread_cond_wait 函数在返回前重新给互斥锁上锁。

定时等待与广播:
pthread_cond_signal只唤醒等待在相应条件变量上的一个线程。
pthread_cond_broadcast唤醒阻塞在相应条件变量上的所有线程。

int pthread_cond_broadcast(pthread_cond_t *cptr);
int pthread_cond_timedwait(pthread_cond_t *cptr, pthread_mutex_t*mptr,
const struct timespec *abstime);
都返回: 成功时为0,出错时为正的Exxx值。
struct timespec
{
time_t tv_sec;
long tv_nsec;
};

互斥锁和条件变量的属性:
互斥锁和条件变量的初始化或摧毁:
int pthread_mutex_init(pthread_mutex_t *mptr, constpthread_mutexattr_t *attr);
int pthread_mutex_destroy(pthread_mutex_t *mptr);
int pthread_cond_init(pthread_cont_t *cptr, constpthread_condattr_t *attr);
int pthread_cond_destroy(pthread_cond_t *cptr);
都返回: 成功时为0,出错时为正的Exxx值。

互斥锁属性的数据类型为pthread_mutexattr_t,条件变量属性的数据类型为pthread_condattr_t,
它们由以下函数初始化或摧毁:
int pthread_mutexattr_init(pthread_mutexattr_t *att);
int pthread_mutexattr_init(pthread_mutexattr_t *att);
int pthread_condattr_init(pthread_condattr_t *att);
int pthread_condattr_init(pthread_condattr_t *att);
都返回: 成功时为0,出错时为正的Exxx值。

int pthread_mutexattr_getpshared(const pthread_mutexattr_t *attr,int *valptr);
int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int*valptr);
int pthread_condattr_getpshared(const pthread_condattr_t *attr, int*valptr);
int pthread_condattr_setpshared(pthread_condattr_t *attr, int*valptr);
都返回: 成功时为0,出错时为正的Exxx值。

指定互斥锁或条件变量在不同进程间共享:
PTHREAD_PROCESS_PRIVATE
PTHREAD_PROCESS_SHARED
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值