多线程控制(条件变量和互斥量)


前言

在多线程中,如果我们不对其进行管理的话,那么各个线程容易陷入混乱状态,从而不能得到我们想要的结果,今天就来介绍两种多线程的管理方式

一、互斥量控制多线程

1.互斥量的介绍

互斥量(mutex)从本质上来说是一把锁,在访问共享资源前对互斥量进行加锁,在访问完成后释放互斥量上的锁。对互斥量进行加锁后,任何其他试图再次对互斥量加锁的线程将会被阻塞直到当前线程释放该互斥锁。如果释放互斥锁时有多个线程阻塞,所有在该互斥锁上的阻塞线程都会变成可运行状态,第一个变为可运行状态的线程可以对互斥量加锁,其他线程将会看到互斥锁依然被锁住,只能回去等待它重新变为可用。在这种方式下,每次只有一个线程可以向前运行。
 
  在设计时需要规定所有的线程必须遵守相同的数据访问规则。只有这样,互斥机制才能正常工作。操作系统并不会做数据访问的串行化。如果允许其中的某个线程在没有得到锁的情况下也可以访问共享资源,那么即使其它的线程在使用共享资源前都获取了锁,也还是会出现数据不一致的问题。
  
  互斥变量用pthread_mutex_t数据类型表示。在使用互斥变量前必须对它进行初始化,可以把它置为常量PTHREAD_MUTEX_INITIALIZER(只对静态分配的互斥量),也可以通过调用pthread_mutex_init函数进行初始化。如果动态地分配互斥量(例如通过调用malloc函数),那么在释放内存前需要调用pthread_mutex_destroy。

2.相关api的介绍

a. 创建及销毁互斥锁
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
int pthread_mutex_destroy(pthread_mutex_t mutex);
// 返回:若成功返回0,否则返回错误编号
 要用默认的属性初始化互斥量,只需把attr设置为NULL。 
  
b 加锁及解锁
#include <pthread.h>
int pthread_mutex_lock(pthread_mutex_t mutex);
int pthread_mutex_trylock(pthread_mutex_t mutex);
int pthread_mutex_unlock(pthread_mutex_t mutex);
// 返回:若成功返回0,否则返回错误编号

如果线程不希望被阻塞,它可以使用pthread_mutex_trylock尝试对互斥量进行加锁。如果调用pthread_mutex_trylock时互斥量处于未锁住状态,那么pthread_mutex_trylock将锁住互斥量,不会出现阻塞并返回0,否则pthread_mutex_trylock就会失败,不能锁住互斥量,而返回EBUSY。

3.编程实战

#include <stdio.h>
#include <pthread.h>



pthread_mutex_t mutex;//定义一把锁

int data=0;//全局变量,线程1,2都能获取


void *func1(void *arg)
{
        int i=0;

        pthread_mutex_lock(&mutex);//加锁

        printf("t1:%ld thread is creat\n",(unsigned long)pthread_self());

        printf("t1 param is %d\n",*((int *)arg));

        while(1){
                printf("t1 data=%d\n",data++);

                sleep(1);

                if(data==3)//利用互斥量来控制线程1在对应的data值退出
                        {
                        pthread_mutex_unlock(&mutex);//解锁
                        pthread_exit(NULL);//退出线程1
                        }

                }

}


void *func2(void *arg)
{
        printf("t2:%ld thread is creat\n",(unsigned long)pthread_self());

        printf("t2 param is %d\n",*((int *)arg));

        while(1){
                printf("t2:data=%d\n",data);
                pthread_mutex_lock(&mutex);//加锁
                data++;                           //这三句话是为了在线程1与线程2竞争时,即使线程2先拿到了锁,也只能让data++,保证线程1能在data=3时退出
                pthread_mutex_unlock(&mutex);//解锁
                sleep(1);
                }

}


int main()
{
        int ret;

        int ret1;

        int param=100;

        pthread_mutex_init(&mutex,NULL);//动态初始化锁

        pthread_t t1;//定义线程

        pthread_t t2;

        ret=pthread_create(&t1,NULL,func1,(void *)&param);

        if(ret==0){
                printf("main:creat t1 success\n");
                }

        ret1=pthread_create(&t2,NULL,func2,(void *)&param);

        if(ret1==0){
                printf("main:creat t2 success\n");
                }

        printf("main:%ld\n",(unsigned long)pthread_self());

        pthread_join(t1,NULL);

        pthread_join(t2,NULL);

        pthread_mutex_destroy(&mutex);//销毁锁
        
        return 0;
}

在liunx平台下编译并运行上述代码
在这里插入图片描述
可以看到t1线程在data=3时就结束了,这就是通过互斥量加锁的方式来控制线程。

二、条件变量控制线程

1.条件变量介绍

条件变量是线程另一可用的同步机制。条件变量给多个线程提供了一个会合的场所。条件变量与互斥量一起使用时,允许线程以无竞争的方式等待特定的条件发生。

条件本身是由互斥量保护的。线程在改变条件状态前必须首先锁住互斥量,其他线程在获得互斥量之前不会察觉到这种改变,因为必须锁定互斥量以后才能计算条件。
  
  条件变量使用之前必须首先初始化,pthread_cond_t数据类型代表的条件变量可以用两种方式进行初始化,可以把常量PTHREAD_COND_INITIALIZER赋给静态分配的条件变量,但是如果条件变量是动态分配的,可以使用pthread_cond_destroy函数对条件变量进行去除初始化(deinitialize)。

2.相关api的介绍

a 创建及销毁条件变量
#include <pthread.h>
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
int pthread_cond_destroy(pthread_cond_t cond);
// 返回:若成功返回0,否则返回错误值。
  除非需要创建一个非默认属性的条件变量,否则pthread_cont_init函数的attr参数可以设置为NULL。
  
b 等待
#include <pthread.h>
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, cond struct timespec *restrict timeout);
// 返回:若成功返回0,否则返回错误编号

pthread_cond_wait等待条件变为真。如果在给定的时间内条件不能满足,那么会生成一个代表一个出错码的返回变量。传递给pthread_cond_wait的互斥量对条件进行保护,调用者把锁住的互斥量传给函数。函数把调用线程放到等待条件的线程列表上,然后对互斥量解锁,这两个操作都是原子操作。这样就关闭了条件检查和线程进入休眠状态等待条件改变这两个操作之间的时间通道,这样线程就不会错过条件的任何变化。pthread_cond_wait返回时,互斥量再次被锁住。
  
  pthread_cond_timedwait函数的工作方式与pthread_cond_wait函数类似,只是多了一个timeout。timeout指定了等待的时间,它是通过timespec结构指定。
  
c 触发
#include <pthread.h>
int pthread_cond_signal(pthread_cond_t cond);
int pthread_cond_broadcast(pthread_cond_t cond);
// 返回:若成功返回0,否则返回错误编号

这两个函数可以用于通知线程条件已经满足。pthread_cond_signal函数将唤醒等待该条件的某个线程,而pthread_cond_broadcast函数将唤醒等待该条件的所有进程。
  
  注意一定要在改变条件状态以后再给线程发信号。

3.代码编程实战

#include <stdio.h>
#include <pthread.h>


pthread_mutex_t mutex;//定义一把锁

pthread_cond_t cond;//定义一个cond条件

int data=0;

void *func1(void *arg)
{
        int i=0;

        pthread_mutex_lock(&mutex);

        printf("t1:%ld thread is creat\n",(unsigned long)pthread_self());

        printf("t1 param is %d\n",*((int *)arg));

        while(1){

                pthread_cond_wait(&cond,&mutex);//等待信号的到来,当信号到来时,再往下执行,否则阻塞。

                printf("t1 run======================\n");

                printf("t1 data=%d\n",data);

                data=0;

                sleep(1);

                }
}


void *func2(void *arg)
{
        printf("t2:%ld thread is creat\n",(unsigned long)pthread_self());

        printf("t2 param is %d\n",*((int *)arg));

        while(1){
                printf("t2:data=%d\n",data);

                pthread_mutex_lock(&mutex);

                data++;

                if(data==3){
                        pthread_cond_signal(&cond);//满足条件时,即向线程1发送信号。
                        }

                pthread_mutex_unlock(&mutex);

                sleep(1);

                }

}



int main()
{

        int ret;

        int ret1;

        int param=100;

        pthread_cond_init(&cond,NULL);//创建条件变量

        pthread_mutex_init(&mutex,NULL);//动态初始化互斥量

        pthread_t t1;

        pthread_t t2;

        ret=pthread_create(&t1,NULL,func1,(void *)&param);

        ret1=pthread_create(&t2,NULL,func2,(void *)&param);

        pthread_join(t1,NULL);
 
        pthread_join(t2,NULL);

        pthread_mutex_destroy(&mutex);//销毁互斥量

        pthread_cond_destroy(&cond);//销毁条件变量

        return 0;
}

在liunx平台下编译并运行这个程序
在这里插入图片描述
可以看到,一开始,线程1是不执行的,当线程2将data的值增加到3时,这个时候就触发了条件变量,然后向线程1发送信号,接受到信号的线程1开始执行,并将data的值重新置为零,这个时候,线程1又被阻塞,线程2重新开始增加data的值,知道它为3,又会将信号传递到线程1之内,其实条件变量算是一种线程间的通信方式。

总结

博主上述对互斥量和条件变量的编程实战只是最简单的一种应用,大家学会多线程控制之后,能够用这两种方式实现更复杂的程序。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值