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

来源:互联网 发布:linux安装时磁盘分区 编辑:程序博客网 时间:2024/06/03 20:15
互斥锁和条件变量出自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