当前位置:首页 > 嵌入式 > 嵌入式软件
[导读]互斥量从本质上说就是一把锁, 提供对共享资源的保护访问。

一、互斥锁

互斥量从本质上说就是一把锁, 提供对共享资源的保护访问。

1. 初始化:

在Linux下, 线程的互斥量数据类型是pthread_mutex_t. 在使用前, 要对它进行初始化:

对于静态分配的互斥量, 可以把它设置为PTHREAD_MUTEX_INITIALIZER, 或者调用pthread_mutex_init.

对于动态分配的互斥量, 在申请内存(malloc)之后, 通过pthread_mutex_init进行初始化, 并且在释放内存(free)前需要调用pthread_mutex_destroy.

原型:

int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restric attr);

int pthread_mutex_destroy(pthread_mutex_t *mutex);

头文件:

返回值: 成功则返回0, 出错则返回错误编号.

说明: 如果使用默认的属性初始化互斥量, 只需把attr设为NULL. 其他值在以后讲解。

2. 互斥操作:

对共享资源的访问, 要对互斥量进行加锁, 如果互斥量已经上了锁, 调用线程会阻塞, 直到互斥量被解锁. 在完成了对共享资源的访问后, 要对互斥量进行解锁。

首先说一下加锁函数:

头文件:

原型:

int pthread_mutex_lock(pthread_mutex_t *mutex);

int pthread_mutex_trylock(pthread_mutex_t *mutex);

返回值: 成功则返回0, 出错则返回错误编号.

说明: 具体说一下trylock函数, 这个函数是非阻塞调用模式, 也就是说, 如果互斥量没被锁住, trylock函数将把互斥量加锁, 并获得对共享资源的访问权限; 如果互斥量被锁住了, trylock函数将不会阻塞等待而直接返回EBUSY, 表示共享资源处于忙状态。

再说一下解所函数:

头文件:

原型:

int pthread_mutex_unlock(pthread_mutex_t *mutex);

返回值: 成功则返回0, 出错则返回错误编号.

3. 死锁:

死锁主要发生在有多个依赖锁存在时, 会在一个线程试图以与另一个线程相反顺序锁住互斥量时发生. 如何避免死锁是使用互斥量应该格外注意的东西。

总体来讲, 有几个不成文的基本原则:

对共享资源操作前一定要获得锁。

完成操作以后一定要释放锁。

尽量短时间地占用锁。

如果有多锁, 如获得顺序是ABC连环扣, 释放顺序也应该是ABC。

线程错误返回时应该释放它所获得的锁。

下面给个测试小程序进一步了解互斥,mutex互斥信号量锁住的不是一个变量,而是阻塞住一段程序。如果对一个mutex变量testlock, 执行了第一次pthread_mutex_lock(testlock)之后,在unlock(testlock)之前的这段时间内,如果有其他线程也执行到了pthread_mutex_lock(testlock),这个线程就会阻塞住,直到之前的线程unlock之后才能执行,由此,实现同步,也就达到保护临界区资源的目的。

#

include

#include

static pthread_mutex_t testlock;

pthread_t test_thread;

void *test()

{

pthread_mutex_lock(&testlock);

printf("thread Test() \n");

pthread_mutex_unlock(&testlock);

}

int main()

{

pthread_mutex_init(&testlock, NULL);

pthread_mutex_lock(&testlock);

printf("Main lock \n");

pthread_create(&test_thread, NULL, test, NULL);

sleep(1); //更加明显的观察到是否执行了创建线程的互斥锁

printf("Main unlock \n");

pthread_mutex_unlock(&testlock);

sleep(1);

pthread_join(test_thread,NULL);

pthread_mutex_destroy(&testlock);

return 0;

}

make

gcc -D_REENTRANT -lpthread -o test test.c

结果:

Main lock

Main unlock

thread Test()

二、条件变量

这里主要说说 pthread_cond_wait()的用法,在下面有说明。

条件变量是利用线程间共享的全局变量进行同步的一种机制,主要包括两个动作:一个线程等待"条件变量的条件成立"而挂起;另一个线程使"条件成立"(给出条件成立信号)。为了防止竞争,条件变量的使用总是和一个互斥锁结合在一起。

1. 创建和注销

条件变量和互斥锁一样,都有静态动态两种创建方式,静态方式使用PTHREAD_COND_INITIALIZER常量,如下:

pthread_cond_t cond=PTHREAD_COND_INITIALIZER

动态方式调用pthread_cond_init()函数,API定义如下:

int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr)

尽管POSIX标准中为条件变量定义了属性,但在LinuxThreads中没有实现,因此cond_attr值通常为NULL,且被忽略。

注销一个条件变量需要调用pthread_cond_destroy(),只有在没有线程在该条件变量上等待的时候才能注销这个条件变量,否则返回EBUSY。因为Linux实现的条件变量没有分配什么资源,所以注销动作只包括检查是否有等待线程。API定义如下:

int pthread_cond_destroy(pthread_cond_t *cond)

2. 等待和激发

int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)

int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)

等待条件有两种方式:无条件等待pthread_cond_wait()和计时等待pthread_cond_timedwait(),其中计时等待方式如果在给定时刻前条件没有满足,则返回ETIMEOUT,结束等待,其中abstime以与time()系统调用相同意义的绝对时间形式出现,0表示格林尼治时间1970年1月1日0时0分0秒。

无论哪种等待方式,都必须和一个互斥锁配合,以防止多个线程同时请求pthread_cond_wait()(或pthread_cond_timedwait(),下同)的竞争条件(Race Condition)。mutex互斥锁必须是普通锁(PTHREAD_MUTEX_TIMED_NP)或者适应锁(PTHREAD_MUTEX_ADAPTIVE_NP),且在调用pthread_cond_wait()前必须由本线程加锁(pthread_mutex_lock()),而在更新条件等待队列以前,mutex保持锁定状态,并在线程挂起进入等待前解锁。在条件满足从而离开pthread_cond_wait()之前,mutex将被重新加锁,以与进入pthread_cond_wait()前的加锁动作对应。 执行pthread_cond_wait()时自动解锁互斥量(如同执行了 pthread_unlock_mutex),并等待条件变量触发。这时线程挂起,不占用 CPU 时间,直到条件变量被触发。

因此,全过程可以描述为:

(1)pthread_mutex_lock()上锁,

(2)pthread_cond_wait()等待,等待过程分解为为:解锁--条件满足--加锁

(3)pthread_mutex_unlock()解锁。

激发条件有两种形式,pthread_cond_signal()激活一个等待该条件的线程,存在多个等待线程时按入队顺序激活其中一个;而pthread_cond_broadcast()则激活所有等待线程。 两者 如果没有等待的线程,则什么也不做。

下面一位童鞋问的问题解释了上面的说明:

当pthread_cond_t调用pthread_cond_wait进入等待状态时,pthread_mutex_t互斥信号无效了.

示例代码如下:

//多线程同步--条件锁(相当与windows的事件)测试

//要先让pthread_cond_wait进入等待信号状态,才能调用pthread_cond_signal发送信号,才有效.

//不能让pthread_cond_signal在pthread_cond_wait前面执行

#include

#include //多线程所用头文件

#include //信号量使用头文件

pthread_cond_t g_cond /*=PTHREAD_MUTEX_INITIALIZER*/; //申明条锁,并用宏进行初始化

pthread_mutex_t g_mutex ;

//线程执行函数

void threadFun1(void)

{

int i;

pthread_mutex_lock(&g_mutex); //1

pthread_cond_wait(&g_cond,&g_mutex); //如g_cond无信号,则阻塞

for( i = 0;i < 2; i++ ){

printf("thread threadFun1.\n");

sleep(1);

}

pthread_cond_signal(&g_cond);

pthread_mutex_unlock(&g_mutex);

}

int main(void)

{

pthread_t id1; //线程的标识符

pthread_t id2;

pthread_cond_init(&g_cond,NULL); //也可以程序里面初始化

pthread_mutex_init(&g_mutex,NULL); //互斥变量初始化

int i,ret;

ret = pthread_create(&id1,NULL,(void *)threadFun1, NULL);

if ( ret!=0 ) { //不为0说明线程创建失败

printf ("Create pthread1 error!\n");

exit (1);

}

sleep(5); //等待子线程先开始

pthread_mutex_lock(&g_mutex); //2

pthread_cond_signal(&g_cond); //给个开始信号,注意这里要先等子线程进入等待状态在发信号,否则无效

pthread_mutex_unlock(&g_mutex);

pthread_join(id1,NULL);

pthread_cond_destroy(&g_cond); //释放

pthread_mutex_destroy(&g_mutex); //释放

return 0;

}

大家请看红颜色的1和2.

明明是1先锁了互斥变量,但代码执行到2还是一样可以锁定.

为什么会这样呢????/

pthread_cond_wait()什么情况才会接锁,继续跑下去啊...现在来看一段典型的应用:看注释即可。

问题解释:当程序进入pthread_cond_wait等待后,将会把g_mutex进行解锁,当离开pthread_cond_wait之前,g_mutex会重新加锁。所以在main中的g_mutex会被加锁。 呵呵。。。

现在来看一段典型的应用:看注释即可。

#include

#include

static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;

static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

struct node {

int n_number;

struct node *n_next;

} *head = NULL;

/*[thread_func]*/

static void cleanup_handler(void *arg)

{

printf("Cleanup handler of second thread.\n");

free(arg);

(void)pthread_mutex_unlock(&mtx);

}

static void *thread_func(void *arg)

{

struct node *p = NULL;

pthread_cleanup_push(cleanup_handler, p);

while (1) {

pthread_mutex_lock(&mtx); //这个mutex主要是用来保证pthread_cond_wait的并发性

while (head == NULL) { //这个while要特别说明一下,单个pthread_cond_wait功能很完善,为何这里要有一个while (head == NULL)呢?因为pthread_cond_wait里的线程可能会被意外唤醒,如果这个时候head != NULL,则不是我们想要的情况。这个时候,应该让线程继续进入pthread_cond_wait

pthread_cond_wait(&cond, &mtx); // pthread_cond_wait会先解除之前的pthread_mutex_lock锁定的mtx,然后阻塞在等待对列里休眠,直到再次被唤醒(大多数情况下是等待的条件成立而被唤醒,唤醒后,该进程会先锁定先pthread_mutex_lock(&mtx);,再读取资源, 用这个流程是比较清楚的/*block-->unlock-->wait() return-->lock*/

#include

#include

#include

#include

#include

#include

#include

#define min(a,b) ((a) < (b) ? (a) : (b))

#define max(a,b) ((a) > (b) ? (a) : (b))

#define MAXNITEMS 1000000

#define MAXNTHREADS 100

int nitems; /* read-only by producer and consumer */

struct {

pthread_mutex_t mutex;

int buff[MAXNITEMS];

int nput;

int nval;

} shared = { PTHREAD_MUTEX_INITIALIZER };

void *produce(void *), *consume(void *);

/* include main */

int

main(int argc, char **argv)

{

int i, nthreads, count[MAXNTHREADS];

pthread_t tid_produce[MAXNTHREADS], tid_consume;

if (argc != 3) {

printf("usage: prodcons3 <#items> <#threads>\n");

return -1;

}

nitems = min(atoi(argv[1]), MAXNITEMS);

nthreads = min(atoi(argv[2]), MAXNTHREADS);

/* 4create all producers and one consumer */

for (i = 0; i < nthreads; i++) {

count[i] = 0;

pthread_create(&tid_produce[i], NULL, produce, &count[i]);

}

pthread_create(&tid_consume, NULL, consume, NULL);

/* 4wait for all producers and the consumer */

for (i = 0; i < nthreads; i++) {

pthread_join(tid_produce[i], NULL);

printf("count[%d] = %d\n", i, count[i]);

}

pthread_join(tid_consume, NULL);

exit(0);

}

/* end main */

void *

produce(void *arg)

{

for ( ; ; ) {

pthread_mutex_lock(&shared.mutex);

if (shared.nput >= nitems) {

pthread_mutex_unlock(&shared.mutex);

return(NULL); /* array is full, we're done */

}

shared.buff[shared.nput] = shared.nval;

shared.nput++;

shared.nval++;

pthread_mutex_unlock(&shared.mutex);

*((int *) arg) += 1;

}

}

/* include consume */

void

consume_wait(int i)

{

for ( ; ; ) {

pthread_mutex_lock(&shared.mutex);

if (i < shared.nput) {

pthread_mutex_unlock(&shared.mutex);

return; /* an item is ready */

}

pthread_mutex_unlock(&shared.mutex);

}

}

void *

consume(void *arg)

{

int i;

for (i = 0; i < nitems; i++) {

consume_wait(i);

if (shared.buff[i] != i)

printf("buff[%d] = %d\n", i, shared.buff[i]);

}

return(NULL);

}

本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除。
换一批
延伸阅读

双系统将是下述内容的主要介绍对象,通过这篇文章,小编希望大家可以对双系统的相关情况以及信息有所认识和了解,详细内容如下。

关键字: 双系统 Windows Linux

安装Linux操作系统并不复杂,下面是一个大致的步骤指南,以帮助您完成安装。1. 下载Linux发行版:首先,您需要从Linux发行版官方网站下载最新的ISO镜像文件。

关键字: Linux 操作系统 ISO镜像

计算机是由一堆硬件组成的,为了有限的控制这些硬件资源,于是就有了操作系统的产生,操作系统是软件子系统的一部分,是硬件基础上的第一层软件。

关键字: Linux 操作系统 计算机

Linux操作系统是一套免费使用和自由传播的类Unix操作系统,通常被称为GNU/Linux。它是由林纳斯·托瓦兹在1991年首次发布的,并基于POSIX和UNIX的多用户、多任务、支持多线程和多CPU的操作系统。Lin...

关键字: Linux 操作系统

所谓进程间通信就是在不同进程之间传播或交换信息,它是一组编程接口,让程序员能够协调不同的进程,使之能在一个操作系统里同时运行,并相互传递、交换信息;还可以让一个程序能够在同一时间里处理许多用户的需求。

关键字: Linux 进程通信 编程接口

串口通信作为一种最传统的通信方式,在工业自动化、通讯、控制等领域得到广泛使用。

关键字: Linux 串口通信 通讯

2023年11月16日: MikroElektronika(MIKROE) ,作为一家通过提供基于成熟标准的创新式硬软件产品来大幅缩短开发时间的嵌入式解决方案公司,今天宣布推出一款基于单线设备的软硬件开源解决方案Cli...

关键字: 嵌入式 Linux 操作系统

Linux是一种免费使用和自由传播的类Unix操作系统,其内核由林纳斯·本纳第克特·托瓦兹于1991年10月5日首次发布。它主要受到Minix和Unix思想的启发,是一个基于POSIX的多用户、多任务、支持多线程和多CP...

关键字: Linux 操作系统

本文中,小编将对嵌入式予以介绍,如果你想对它的详细情况有所认识,或者想要增进对它的了解程度,不妨请看以下内容哦。

关键字: 嵌入式 Linux

在这篇文章中,小编将为大家带来嵌入式 Linux的相关报道。如果你对本文即将要讲解的内容存在一定兴趣,不妨继续往下阅读哦。

关键字: 嵌入式 Linux
关闭
关闭