线程的同步-互斥量、读写锁及条件变量

互斥量
  当多个线程共享相同的内存时,需要每一个线程看到相同的视图。当一个线程修改变量时,而其他线程也可以读取或者修改这个变量,就需要对这些线程同步,确保他们不会访问到无效的变量。

  为了让线程访问数据不产生冲突,这要就需要对变量加锁,使得同一时刻只有一个线程可以访问变量。互斥量本质就是锁,访问共享资源前对互斥量加锁,访问完成后解锁。
  当互斥量加锁以后,其他所有需要访问该互斥量的线程都将阻塞。

互斥量用pthread_mutex_t类型的数据表示,在使用之前需要对互斥量初始化
  1)、如果是动态分配的互斥量,可以调用pthread_mutex_init()函数初始化
  2)、如果是静态分配的互斥量,还可以把它置为常量PTHREAD_MUTEX_INITIALIZER
  3)、动态分配的互斥量在释放内存之前需要调用pthread_mutex_destroy()

pthread_mutex_init函数: 互斥量的初始化
原函数:int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr)
参数:mutex,要初始化的互斥量
   attr,互斥量的属性(可以写NULL)
返回值:成功返回0,失败返回错误码

pthread_mutex_destory函数: 互斥量的销毁函数
原函数:int pthread_mutex_destory(pthread_mutex_t *mutex)
参数:mutex,要销毁的互斥量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER(静态的方式);

pthread_mutex_lock函数: 加锁函数
原函数:int pthread_mutex_lock(pthread_mutex_t *mutex)
参数:mutex,要加锁的互斥量
返回值:成功返回0,失败返回错误码
注:如果互斥量已经被锁住,那么会导致该线程阻塞。

pthread_mutex_trylock函数: 尝试加锁函数
原函数:int pthread_mutex_trylock(pthread_mutex_t *mutex)
参数:mutex,要加锁的互斥量
返回值:成功返回0,失败返回错误码
注:如果互斥量已经被锁住,不会导致线程阻塞。

pthread_mutex_unlock函数: 解锁函数
原函数:int pthread_mutex_unlock(pthread_mutex_t *mutex)
参数:要解锁的互斥量
返回值:成功返回0,失败返回错误码
注:如果一个互斥量没有被锁住(加锁函数和解锁函数要成对出现),那么解锁就会出错。

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
//创建一个结构体,数据类型都一样是为了方便赋值
struct student
{
        int id;
        int age;
        int name;
 
}stu;
//定义两个全局变量,因为两个线程都要使用
int i;
pthread_mutex_t mutex;
void *thread_fun1(void *arg)
{
        while(1)
        {
                //加锁,对整个结构体访问进行加锁,防止产生错码
                pthread_mutex_lock(&mutex);
                stu.id = i;
                stu.age = i;
                stu.name = i;
                i++;
                if(stu.id !=stu.age || stu.id !=stu.name || stu.age!=stu.name)
                {
                        printf("thread 1 %d,%d,%d\n", stu.id, stu.age, stu.name);
                        break;
                }
                //访问变量完成,需要进行解锁,只有这样其他线程才能访问
                pthread_mutex_unlock(&mutex);
 
        }
 
        return (void *)0;
}
void *thread_fun2(void *arg)
{ 
        while(1)
        {
                pthread_mutex_lock(&mutex);
                stu.id = i;
                stu.age = i;
                stu.name = i;
                i++;
                if(stu.id !=stu.age || stu.id !=stu.name || stu.age!=stu.name)
                {
                        printf("thread 2 %d,%d,%d\n", stu.id, stu.age, stu.name);
                        break;
                }
 
                pthread_mutex_unlock(&mutex);
        }
        return (void *)0;
}
int main()
{
        pthread_t tid1,tid2;
        int err;
        //对互斥量进行初始化,只有初始化过后互斥量才能使用
        err = pthread_mutex_init(&mutex,NULL);
        if(err != 0)
        {
                printf("init mutex failure\n");
                return 1;
        }
        //创建新的线程
        err = pthread_create(&tid1,NULL,thread_fun1,NULL);
        if(err != 0)
        {
                printf("create new thread failure\n");
                return 1;
        }
        //创建新的线程
        err = pthread_create(&tid1,NULL,thread_fun1,NULL);
        if(err != 0)
        {
                printf("create new thread failure\n");
                return 1;
        }
        //等待新线程运行结束
        pthread_join(tid1,NULL);
        pthread_join(tid2,NULL);
 
        return 0;
}

运行结果:无打印信息

读写锁
  读写锁与互斥量类似,不过读写锁有更高的并行性。互斥量要么加锁要么不加锁,而且同一时刻只允许一个线程对其加锁。对于一个变量的读取,完全可以让多个线程同时进行操作。
  变量类型:pthread_rwlock_t *rwlock
读写锁有三种状态,读模式下加锁,写模式下加锁,不加锁。一次只有一个线程可以占有写模式下的读写锁,但是多个线程可以同时占有读模式的读写锁。
  读写锁在写加锁状态时,在它被解锁之前,所有试图对这个锁加锁的线程都会阻塞。读写锁在读加锁状态时,所有试图以读模式对其加锁的线程都会获得访问权,但是如果线程希望以写模式对其加锁,它必须阻塞直到所有的线程释放锁。当读写锁以读模式加锁时,如果有线程试图以写模式对其加锁,那么读写锁会阻塞随后的读模式锁请求。这样可以避免读锁长期占用,而写锁达不到请求。
  读写锁非常适合对数据结构读次数大于写次数的程序,当它以读模式锁住时,是以共享的方式锁住的;当它以写模式锁住时,是以独占的模式锁住的。

pthread_rwlock_init函数: 读写锁初始化
原函数:int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr)
参数:rwlock,要初始化的锁
   attr,锁属性(可写NULL)
返回值:成功返回0,失败返回错误码

pthread_rwlpck_destory函数: 读写锁销毁
原函数:int pthread_rwlock_destroy(pthread_rwlock_t *rwlock)
参数:rwlock,要销毁的锁
返回值:成功返回0,失败返回错误码

pthread_rwlock_rdlock函数: 读模式加锁
原函数:int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock)
参数:rwlock,要加锁的锁
返回值:成功返回0,失败返回错误码

pthread_rwlock_tryrdlock函数: 尝试读模式加锁
原函数:int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock)
参数:要加锁的锁
返回值:成功返回0,失败返回错误码

pthread_rwlock_wrlock函数: 写模式加锁
原函数:int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock)
参数:要加锁的锁
返回值:成功返回0,失败返回错误码

pthread_rwlock_trywrlock函数: 尝试写模式加锁
原函数:int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock)
参数:要加锁的锁
返回值:成功返回0,失败返回错误码

pthread_rwlock_unlock函数: 解锁函数
原函数:int pthread_rwlock_unlock(pthread_rwlock_t *rwlock)
参数:要解锁的锁
返回值:成功返回0,失败返回错误码

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
 
//定义一个全局锁
pthread_rwlock_t rwlock;
int num=0;
void *thread_fun1(void *arg)
{
        //读加锁        
//      pthread_rwlock_rdlock(&rwlock);
        //写加锁
        pthread_rwlock_wrlock(&rwlock);
        printf("the first thread print %d\n",num);
        sleep(5);
 
        printf("the first thread over\n");
        //解锁
        pthread_rwlock_unlock(&rwlock);
 
        return (void *)1;
}
void *thread_fun2(void *arg)
{
        //读加锁        
//      pthread_rwlock_rdlock(&rwlock);
        //写加锁
        pthread_rwlock_wrlock(&rwlock);
        printf("the second thread print %d\n",num);
        sleep(5);
 
        printf("the second thread over\n");
        //解锁
        pthread_rwlock_unlock(&rwlock);
 
        return (void *)2;
}
int main()
{
        pthread_t tid1,tid2;
        int err;
        //初始化读写锁
        err=pthread_rwlock_init(&rwlock,NULL);
        if(err != 0)
        {
                printf("init rwlock failure\n");
                return 1;
        }
        //创建新的线程
        err=pthread_create(&tid1,NULL,thread_fun1,NULL);
        if(err != 0)
        {
                printf("create new firest thread failure\n");
                return 1;
        }
        err=pthread_create(&tid2,NULL,thread_fun2,NULL);
        if(err != 0)
        {
                printf("create new second thread failure\n");
                return 1;
        }
        //等待新线程执行完毕
        pthread_join(tid1,NULL);
        pthread_join(tid2,NULL);
        //读写锁的销毁
        pthread_rwlock_destroy(&rwlock);
        return 0;
}

运行结果

the first thread print 0
the first thread over
the second thread print 0
the second thread over

条件变量
  我们需要一种机制,当互斥量被锁住以后发现当前线程还是无法完成自己的操作,那么它应该释放互斥量,让其他线程工作。
  1)可以采用轮询的方式,不停的查询你需要的条件
  2)让系统来帮你查询条件,使用条件变量pthread_cond_t cond

pthread_cond_init函数: 条件变量初始化
原函数:int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr)
参数:cond,要初始化的条件变量
   attr,条件变量属性(默认属性为NULL)
返回值:成功返回0,失败返回错误码

pthread_cond_destory函数: 条件变量销毁
原函数:int pthread_cond_destroy(pthread_cond_t *cond)
参数:要销毁的条件变量
返回值:成功返回0,失败返回错误码

pthread_cond_wait函数: 等待条件变量被设置
原函数:int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex)
参数:cond,要设置的条件变量
   mutex,互斥量
返回值:成功返回0,失败返回错误码

  使用pthread_cond_wait等待条件变为真。传递给pthread_cond_wait的互斥量对条件进行保护,调用者把锁住的互斥量传递给函数。
  pthread_cond_wait函数将线程放到等待条件的线程列表上,然后对互斥量进行解锁,这是个原子操作。当条件满足时这个函数返回,返回以后继续对互斥量加锁。

pthread_cond_timedwait函数: 等待条件变量被设置(指定等待时间)
原函数:int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime)
参数:cond,要设置的条件变量
   mutex,互斥量
   abstime,等待的时间
返回值:成功返回0,失败返回错误码

时间用下面的结构体表示:
struct timespec{
        time_t tv_sec;
        long tv_nsec;
       };

  pthread_cond_timedwait函数与pthread_cond_wait类似,只是多一个timeout,如果到了指定的时间条件还不满足,那么就返回。注意,这个时间是绝对时间。例如你要等待3分钟,就要把当前时间加上3分钟然后转换到timespec,而不是直接将3分钟转换到 timespec。

当条件满足的时候,需要唤醒等待条件的线程

1)pthread_cond_broadcast函数: 唤醒等待条件的所有线程,用于设置条件变量,即使得事件发生,这样等待该事件的线程将不再阻塞
原函数:int pthread_cond_broadcast(pthread_cond_t *cond)
参数:cond,条件变量

2)pthread_cond_signal函数: 至少唤醒等待条件的某一个线程,用于解除某一个等待线程的阻塞状态
原函数:int pthread_cond_signal(pthread_cond_t *cond)
参数:cond,条件变量

注:一定要在条件改变以后再唤醒线程

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
 
#define BUFFER_SIZE   5     //产品库存大小
#define PRODUCT_CNT   30    //产品生产总数
 
struct product_cons
{
        int buffer[BUFFER_SIZE];  //生产产品值
        pthread_mutex_t lock;   //互斥锁
        int readpos,writepos;   //读写位置
        pthread_cond_t notempty;//条件变量,非空
        pthread_cond_t notfull;//条件变量,非满
}buffer;
 
void init(struct product_cons *p)//初始化函数
{
        pthread_mutex_init(&p->lock,NULL);//初始化互斥锁
        pthread_cond_init(&p->notempty,NULL);//初始化条件变量
        pthread_cond_init(&p->notfull,NULL);//初始化条件变量
        p->readpos = 0;
        p->writepos = 0;
}
void finish(struct product_cons *p)//销毁函数
{
        pthread_mutex_destroy(&p->lock);//销毁互斥锁
        pthread_cond_destroy(&p->notempty);//销毁条件变量
        pthread_cond_destroy(&p->notfull);//销毁条件变量
        p->readpos = 0;                 //复位读指针复位
        p->writepos = 0;                //复位写指针复位
}
//存储一个数据到buffer
void put(struct product_cons *p,int data)//输入产品子函数
{
        pthread_mutex_lock(&p->lock);
        if((p->writepos+1)%BUFFER_SIZE == p->readpos)
        {
                printf("producer wait for not full\n");
                pthread_cond_wait(&p->notfull,&p->lock);
        }
 
        p->buffer[p->writepos] = data;
        p->writepos++;
        if(p->writepos >= BUFFER_SIZE)
                p->writepos = 0;
 
        pthread_cond_signal(&p->notempty);
        pthread_mutex_unlock(&p->lock);
}
//读,从buffer移除一个数据
int get(struct product_cons *p)
{
        int data;
        pthread_mutex_lock(&p->lock);
 
        if(p->readpos == p->writepos)
        {
                printf("consumer wait for not empty\n");
                pthread_cond_wait(&p->notempty,&p->lock);
        }
        data=p->buffer[p->readpos];
        p->readpos++;
        if(p->readpos >=BUFFER_SIZE)
                p->readpos = 0;
 
        pthread_cond_signal(&p->notfull);
        pthread_mutex_unlock(&p->lock);
 
        return data;
}
void *producer(void *data)//子线程,生产
{
        int n;
        for(n=1;n<30;n++)
        {
                sleep(1);
                printf("put the %d product.....\n",n);
                put(&buffer,n);
                printf("put the %d protuct sucess\n",n);
        }
 
        printf("producer stopped\n");
        return NULL;
}
void *consumer(void *data)  //子线程,购买
{
        static int cnt = 0;
        int num;
        while(1)
        {
                sleep(2);
                printf("get  product ...\n");
                num = get(&buffer);
                printf("get the %d product success\n", num);
                if(++cnt == PRODUCT_CNT)
                        break;
        }
 
        printf("consumer stopped\n");
        return NULL;
}
int main(int argc, char *argv[])
{
        pthread_t th_a,th_b;
        void *retval;
        //调用初始化函数
        init(&buffer);
        //创建新的线程
        pthread_create(&th_a, NULL, producer, 0);
        pthread_create(&th_b, NULL, consumer, 0);
        //链接新的线程
        pthread_join(th_a, &retval);
        pthread_join(th_b, &retval);
        //调用销毁函数
        finish(&buffer);
 
        return 0;
}

运行结果

put the 1 product.....
put the 1 protuct sucess
get  product ...
get the 1 product success
put the 2 product.....
put the 2 protuct sucess
put the 3 product.....
put the 3 protuct sucess
get  product ...
get the 2 product success
put the 4 product.....
put the 4 protuct sucess
put the 5 product.....
put the 5 protuct sucess
get  product ...
get the 3 product success
put the 6 product.....
put the 6 protuct sucess
put the 7 product.....
put the 7 protuct sucess
get  product ...
get the 4 product success
put the 8 product.....
put the 8 protuct sucess
put the 9 product.....
producer wait for not full
get  product ...
get the 5 product success
put the 9 protuct sucess
put the 10 product.....
producer wait for not full
get  product ...
get the 6 product success
put the 10 protuct sucess
put the 11 product.....
producer wait for not full
get  product ...
get the 7 product success
put the 11 protuct sucess
put the 12 product.....
producer wait for not full
^C
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值