目录
12、POSIX线程同步技术
1、线程同步
- 两个(或多个)线程同时执行时,经常需要访问到公共资源或代码的关键部分,这时就涉及到了线程的同步问题,我们可以通过下面两种方法来更好地控制线程的执行情况和更好地访问代码的关键部分
- 信号量
- 互斥量
用信号量进行同步
-
"信号量"的作用就象是代码周围的门卫
-
二进制信号量:一种最简单的一种信号量,只有 0 , 1 两种取值
-
计数信号量:有更大的取值范围,一般用于希望有限个线程去执行一段给定的代码
信号量函数
- 头文件 <semaphore.h>
- 信号量函数的名字都以"sem_"打头
- 信号量对象用sem_t表示
2、sem_init函数创建一个信号量
- 作用:对给定的信号量对象进行初始化
int sem_init(sem_t *sem,int pshared,unsigned value);
- 参数
- sem: 要进行初始化的信号量对象
- pshared:控制着信号量的类型,如果值为0,表示它是当前进程的局部信号量;否则,其他进程就能够共享这个信号量
- value:赋给信号量对象的一个整数类型的初始值
- 返回:成功返回 0;
3、sem_post函数
- 作用:给信号量的值加上一个"1"
int sem_post(sem_t *sem);
- 参数
- sem: 初始化的信号量对象的指针作为参数,用来改变该对象的值
- 返回值
- 成功:返回 0;
是一个"原子操作"( 不会被线程调度机制打断的操作 )-即同时对同一个信号量做加"1"操作的两个线程是不会冲突的。信号量的值永远会正确地加上一个"2",因为有两个线程试图改变它
4、sem_wait函数
- 作用:从信号量的值减去一个"1",但它永远会先等待该信号量为一个非零值才开始做减法
int sem_wait(sem_t *sem);
- 参数
- sem: 初始化的信号量对象的指针作为参数,用来改变该对象的值
- 返回值:成功,0
也是一个"原子操作"
5、sem_destroy函数
- 作用:用完信号量后,对该信号量进行清理
int sem_destroy(sem_t *sem);
- 参数
- sem: 初始化的信号量对象的指针作为参数,用来改变该对象的值
- 返回值:成功,0
归还自己占有的一切资源,在清理信号量的时候如果还有线程在等待它,用户就会收到一个错误
6、信号量实现生产者消费者模型
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>
#define NUM 5
int queue[NUM]; //定义全局变量实现环形队列
sem_t blank_number, product_number;//空格信号量,产品信号量
void *producer(void *arg)
{
int p = 0;
while (1)
{
sem_wait(&blank_number); //生产者将空格数--,为0则阻塞等待
queue[p] = rand() % 1000 + 1; //生产一个产品
printf("Produce %d\n", queue[p]);
sem_post(&product_number); //将产品数++
p = (p+1)%NUM;
sleep(rand()%5);
}
return NULL;
}
void *consumer(void *arg)
{
int c = 0;
while (1)
{
sem_wait(&product_number); //消费者将产品数--
printf("Consume %d\n", queue[c]);
queue[c] = 0; //消费一个产品
sem_post(&blank_number); //空格数++,消费掉
c = (c+1)%NUM;
sleep(rand()%5);
}
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t pid, cid;
sem_init(&blank_number, 0, NUM);//初始化空格信号量为5
sem_init(&product_number, 0, 0);//产品数为0
pthread_create(&pid, NULL, producer, NULL);
pthread_create(&cid, NULL, consumer, NULL);
pthread_join(pid, NULL);
pthread_join(cid, NULL);
sem_destroy(&blank_number);
sem_destroy(&product_number);
return 0;
}
7、用互斥量进行同步
- 使用互斥量是实现多线程程序中的同步访问的另一种手段
- 程序员给某个对象加上一把“锁”,每次只允许一个线程去访问它
- 如果想对代码关键部分的访问进行控制,你必须在进入这段代码之前锁定一把互斥量,在完成操作后再打开它
互斥量函数组
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int pthread_mutex_init(pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
示例
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NLOOP 5000
int counter; /* incremented by threads */
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
void *doit(void *);
int main(int argc, char **argv)
{
pthread_t tidA, tidB;
pthread_create(&tidA, NULL, &doit, NULL);
pthread_create(&tidB, NULL, &doit, NULL);
/* wait for both threads to terminate */
pthread_join(tidA, NULL);
pthread_join(tidB, NULL);
return 0;
}
void *doit(void *vptr)
{
int i, val;
for (i = 0; i < NLOOP; i++) {
//pthread_mutex_lock(&counter_mutex);
val = counter;
val++;
printf("%x: %d\n", (unsigned int)pthread_self(), val);
counter = val;
//pthread_mutex_unlock(&counter_mutex);
}
return NULL;
}
8、条件变量
- 条件变量用来自动阻塞一个线程,直到某特殊情况发生为止。通常条件下变量和互斥锁同时使用。
- 条件变量是用来等待事件。
//初始化条件变量
int pthread_cond_init(pthread_cond_t *cond,pthread_condattr_t *cond_attr);
//自动释放mutex锁,等待条件满足
int pthread_cond_wait(pthread_cond_t *cond,pthread_mutex_t *mutex);
//自动释放mutex锁,等待条件满足,如果在abstime时间内还没有满足,则返回错误
int pthread_cond_timewait(pthread_cond_t *cond,pthread_mutex *mutex,const timespec *abstime);
//销毁条件变量
int pthread_cond_destroy(pthread_cond_t *cond);
//让等待条件满足的线程中某一个被唤醒
int pthread_cond_signal(pthread_cond_t *cond);
//让等待条件满足的线程中全部被唤醒
int pthread_cond_broadcast(pthread_cond_t *cond);
9、条件变量加互斥锁实现生产者消费者模型
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <semaphore.h>
#define ERR_EXIT(m) do { perror(m);exit(EXIT_FAILURE); } while(0)
int nready=0;
pthread_mutex_t g_mutex;
pthread_cond_t g_cond;
pthread_t tid[10];
void *produce(void *data)
{
int i;
long n=(long)data;
for(i=0;i<3;i++)
{
pthread_mutex_lock(&g_mutex);
nready++;
printf("%ld produce nready=%d\n",n,nready);
pthread_cond_signal(&g_cond);
pthread_mutex_unlock(&g_mutex);
sleep(4);
}
return NULL;
}
void *cust(void *data)
{
int i;
long n=(long)data;
for(i=0;i<3;i++)
{
pthread_mutex_lock(&g_mutex);
while(nready<=0)
{
printf("%ld cust wait for a cond\n",n);
sleep(1);
pthread_cond_wait(&g_cond,&g_mutex);
}
--nready;
printf("%ld cust nready=%d\n",n,nready);
pthread_mutex_unlock(&g_mutex);
sleep(1);
}
return NULL;
}
int main(int argc,char *argv[])
{
pthread_mutex_init(&g_mutex,NULL);
pthread_cond_init(&g_cond,NULL);
int i;
for(i=0;i<5;i++)
pthread_create(&tid[i],NULL,produce,(void *)&i);
for(i=0;i<5;i++)
pthread_create(&tid[i+5],NULL,cust,(void *)&i);
for(i=0;i<10;i++)
pthread_join(tid[i],NULL);
pthread_cond_destroy(&g_cond);
pthread_mutex_destroy(&g_mutex);
return 0;
}
10、信号量、互斥量、条件变量封装
//locker.h
#ifndef LOCKER_H
#define LOCKER_H
#include <exception>//异常处理
#include <pthread.h>
#include <semaphore.h>
#include <iostream>
#include <cstdlib>
/*封装信号量的类*/
class Sem
{
public:
Sem()
{
if(sem_init(&m_sem,0,0) != 0){
std::cout<<"Error:sem_init"<<std::endl;
exit(1);
}
}
~Sem()
{
sem_destroy(&m_sem);
}
bool wait()
{
return sem_wait(&m_sem) == 0;
}
bool post()
{
return sem_post(&m_sem) == 0;
}
private:
sem_t m_sem;
};
/*封装互斥锁的类*/
class Locker
{
public:
Locker()
{
if(pthread_mutex_init(&m_mutex,NULL) != 0){
std::cout<<"Error:pthread_mutex_init"<<std::endl;
exit(1);
}
}
~Locker()
{
pthread_mutex_destroy(&m_mutex);
}
bool lock()
{
return pthread_mutex_lock(&m_mutex) == 0;
}
bool unlock()
{
return pthread_mutex_unlock(&m_mutex) == 0;
}
private:
pthread_mutex_t m_mutex;
};
/*封装条件变量*/
class Cond
{
public:
Cond()
{
if(pthread_mutex_init(&m_mutex,NULL) != 0){
std::cout<<"Error:pthread_mutex_init"<<std::endl;
exit(1);
}
if(pthread_cond_init(&m_cond,NULL) != 0){
pthread_mutex_destroy(&m_mutex);
std::cout<<"Error:pthread_cond_init"<<std::endl;
exit(1);
}
}
~Cond()
{
pthread_mutex_destroy(&m_mutex);
pthread_cond_destroy(&m_cond);
}
bool wait()
{
int ret = 0;
pthread_mutex_lock(&m_mutex);
ret = pthread_cond_wait(&m_cond,&m_mutex);
pthread_mutex_unlock(&m_mutex);
return ret == 0;
}
bool signal()
{
return pthread_cond_signal(&m_cond) == 0;
}
private:
pthread_mutex_t m_mutex;
pthread_cond_t m_cond;
};
#endif