互斥锁的概念和使用方法。

声明:转载别人的,觉得对自己有用。链接地址:http://blog.youkuaiyun.com/harry_lyc/article/details/6222920

在单线程条件下,由于对数据操作,在同样的时间下,只有一个线程来操作。所以不用担心数据的同步问题。现代的操作系统,大都提供并发机制,虽然有时候是表面的并发。在Linux中,并发用的最多的是基于线程的并发,进程的代价太高了,这样,一个共享的数据,在同一时间内,可能有多个线程在操作。如果没有同步机制,那么想要保证每个线程操作的正确性,是很困难的。

1互斥锁概念:

互斥锁提供一个可以在同一时间,只让一个线程访问临界资源的的操作接口。互斥锁(Mutex)是个提供线程同步的基本锁。让上锁后,其他的线程如果想要锁上,那么会被阻塞,直到锁释放后(说明,一般会把访问共享内存这段代码放在上锁程序之后。)。

如果,在锁释放后,有多个线程被阻塞,那么,所有的被阻塞的线程会被设为可执行状态。第一个执行的线程,取得锁的控制权,上锁。其他的线程继续阻塞。

2:互斥锁系统原型

互斥锁的系统原型为:pthread_mutex_t,在用互斥锁之前,必须要初始化互斥锁,可以调用pthread_mutex_init;或者是PTHREAD_MUTEX_INITIALZER(仅用于静态分配内存)如果我们动态分配互斥锁(比如,用malloc),那么,在释放内存之前,必须调用pthread_mutex_destroy;

下面为互斥锁初始化和销毁的函数原型:

#include <pthread.h>

int pthread_mutex_init(pthread_mutex_t *restrict mutex,

                   const pthread_mutexattr_t *restrict attr);

int pthread_mutex_destroy(pthread_mutex_t *mutex);

Both return: 0 if OK, error number on failure

互斥锁的上锁和解锁的函数原型为:

#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);

All return: 0 if OK, error number on failure

如果要锁上一个互斥锁用pthread_mutex_lock;解锁用pthread_mutex_unlock;如果,一个线程不想被阻止,那么可以用pthread_mutex_trylock函数来上锁。如果一个线程调用pthread_mutex_trylock时,锁变量没有被其他的线程锁上,那么pthread_mutex_trylock会锁上锁变量,返回值0,表示成功。否则,pthread_mutex_trylock失败,返回EBUSY,没有上锁。

下面为一个使用互斥锁来实现,共享数据同步例子。在程序中有一个全局变量g_value,和互斥锁mutex,在线程1中,重置g_value值为0,然后加5;在线程2中,重置g_value值为0,然后加6;最后在主线程中输出g_value的值,这是g_value的值为最后线程修改过的值。

[cpp]  view plain copy
  1. #include<stdio.h>  
  2. #include<pthread.h>  
  3.   
  4. void  fun_thread1(char * msg);  
  5. void  fun_thread2(char * msg);  
  6. int g_value = 1;  
  7. pthread_mutex_t mutex;  
  8. /*in the thread individual, the thread reset the g_value to 0,and add to 5 int the thread1,add to 6 in the thread2.*/  
  9. int main(int argc, char * argv[])  
  10. {  
  11.     pthread_t thread1;  
  12.     pthread_t thread2;  
  13.     if(pthread_mutex_init(&mutex,NULL) != 0 )  
  14.     {  
  15.         printf("Init metux error.");  
  16.         exit(1);  
  17.     }  
  18.     if(pthread_create(&thread1,NULL,(void *)fun_thread1,NULL) != 0)  
  19.     {  
  20.         printf("Init thread1 error.");  
  21.         exit(1);  
  22.     }  
  23.     if(pthread_create(&thread2,NULL,(void *)fun_thread2,NULL) != 0)  
  24.     {  
  25.         printf("Init thread2 error.");  
  26.         exit(1);  
  27.     }  
  28.     sleep(1);  
  29.     printf("I am main thread, g_vlaue is %d./n",g_value);  
  30.     return 0;  
  31. }  
  32. void  fun_thread1(char * msg)  
  33. {  
  34.     int val;  
  35.     val = pthread_mutex_lock(&mutex);/*lock the mutex*/  
  36.     if(val != 0)  
  37.     {  
  38.         printf("lock error.");  
  39.     }  
  40.     g_value = 0;/*reset the g_value to 0.after that add it to 5.*/  
  41.     printf("thread 1 locked,init the g_value to 0, and add 5./n");  
  42.     g_value += 5;  
  43.     printf("the g_value is %d./n",g_value);  
  44.     pthread_mutex_unlock(&mutex);/*unlock the mutex*/  
  45.     printf("thread 1 unlocked./n");  
  46. }  
  47. void  fun_thread2(char * msg)  
  48. {     
  49.     int val;  
  50.     val = pthread_mutex_lock(&mutex);/*lock the mutex*/  
  51.     if(val != 0)  
  52.     {  
  53.         printf("lock error.");  
  54.     }  
  55.     g_value = 0;/*reset the g_value to 0.after that add it to 6.*/  
  56.     printf("thread 2 locked,init the g_value to 0, and add 6./n");  
  57.     g_value += 6;  
  58.     printf("the g_value is %d./n",g_value);  
  59.     pthread_mutex_unlock(&mutex);/*unlock the mutex*/  
  60.     printf("thread 2 unlocked./n");  
  61. }  

ubuntu10.4Thread model: posix,gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5)编译,运行如下:

thread 2 locked,init the g_value to 0, and add 6.

the g_value is 6.

thread 2 unlocked.

thread 1 locked,init the g_value to 0, and add 5.

the g_value is 5.

thread 1 unlocked.

I am main thread, g_vlaue is 5.

总结:

关于互斥锁,可能有些地方,不太容易懂。比如,互斥锁锁什么?简单的来说,互斥锁用的限制在同一时刻,其他的线程执行pthread_mutex_lockpthread_mutex_unlock之间的指令。

<think>好的,用户让我介绍一下FreeRTOS中互斥锁使用方法。首先,我需要回想一下之前用户的问题,他们之前问过二值信号量,现在转向互斥锁,可能是在实际项目中遇到了资源管理的问题,或者想更深入地了解FreeRTOS的同步机制。 用户可能是嵌入式开发者,正在使用FreeRTOS进行多任务开发,需要确保共享资源的安全访问。互斥锁在FreeRTOS中用于解决优先级反转问题,而二值信号量可能无法处理这种情况,所以用户可能已经遇到了优先级反转的问题,或者想预防这种情况。 接下来,我需要考虑如何组织回答。应该从基本概念开始,然后逐步深入使用方法,包括创建、获取、释放、递归互斥锁,以及注意事项最佳实践。用户可能需要具体的代码示例,所以提供实际的代码片段会很有帮助。 同时,用户之前的问题中提到过二值信号量,所以需要对比互斥锁二值信号量的区别,避免混淆。另外,用户可能关心互斥锁的特殊机制,比如优先级继承,这也是FreeRTOS互斥锁的重要特性,需要强调。 还需要注意常见的错误用法,比如在中断中使用互斥锁,或者在获取后未释放,导致死锁。这些是开发者容易出错的地方,提醒用户注意这些点会很有用。 最后,确保回答结构清晰,分步骤讲解,让用户能够逐步理解应用。同时,提供示例代码场景分析,帮助用户更好地掌握互斥锁使用方法。</think>以下是FreeRTOS互斥锁(Mutex)使用方法的详细分步说明: --- ### **1. 互斥锁的核心特性** FreeRTOS的互斥锁在二值信号量基础上增加了**优先级继承**机制,专门用于解决多任务共享资源访问时的优先级反转问题。 --- ### **2. 使用流程分解** #### **步骤1:创建互斥锁** ```c SemaphoreHandle_t xMutex = xSemaphoreCreateMutex(); // 创建基础互斥锁 SemaphoreHandle_t xRecursiveMutex = xSemaphoreCreateRecursiveMutex(); // 创建递归互斥锁 ``` - **返回值**:若创建成功返回句柄,失败返回`NULL` #### **步骤2:获取互斥锁** ```c // 阻塞模式(永久等待) if (xSemaphoreTake(xMutex, portMAX_DELAY) == pdTRUE) { // 成功获取锁,访问共享资源 } // 带超时的非阻塞模式(等待100ms) if (xSemaphoreTake(xMutex, pdMS_TO_TICKS(100)) == pdTRUE) { // 成功获取锁 } else { // 超时处理 } // 递归锁专用API(允许同一任务多次获取) xSemaphoreTakeRecursive(xRecursiveMutex, portMAX_DELAY); ``` #### **步骤3:释放互斥锁** ```c xSemaphoreGive(xMutex); // 释放基础互斥锁 xSemaphoreGiveRecursive(xRecursiveMutex); // 释放递归锁(需与TakeRecursive配对) ``` - **规则**:必须由获取锁的任务释放,否则触发断言错误 --- ### **3. 典型代码场景** #### **场景1:保护全局变量** ```c SemaphoreHandle_t counterMutex; void TaskA(void *pvParam) { counterMutex = xSemaphoreCreateMutex(); while(1) { if (xSemaphoreTake(counterMutex, 100) == pdTRUE) { global_counter++; xSemaphoreGive(counterMutex); } vTaskDelay(10); } } ``` #### **场景2:递归访问控制** ```c void NestedFunction(SemaphoreHandle_t mutex) { xSemaphoreTakeRecursive(mutex, portMAX_DELAY); // 执行嵌套操作 xSemaphoreGiveRecursive(mutex); } void MainTask() { SemaphoreHandle_t recursiveMutex = xSemaphoreCreateRecursiveMutex(); xSemaphoreTakeRecursive(recursiveMutex, portMAX_DELAY); NestedFunction(recursiveMutex); // 允许递归获取 xSemaphoreGiveRecursive(recursiveMutex); } ``` --- ### **4. 关键注意事项** | 要点 | 说明 | |---------------------|--------------------------------------------------------------------| | **优先级继承** | 当低优先级任务持有锁时,若高优先级任务等待,低优先级任务会临时提升优先级 | | **禁止中断中使用** | 互斥锁不能在ISR中获取/释放,需用信号量+中断延迟处理 | | **死锁预防** | 避免任务同时获取多个锁时形成环形依赖 | | **锁持有时间** | 保持锁的时间应尽量短,建议仅包裹直接操作共享资源的代码段 | --- ### **5. 与二值信号量的对比** | 特性 | 互斥锁 | 二值信号量 | |---------------------|-------------------------------|---------------------------| | 所有权 | 必须由获取者释放 | 任何任务均可释放 | | 优先级处理 | 支持优先级继承 | 无特殊机制 | | 递归获取 | 支持(需递归互斥锁) | 不支持 | | 典型用途 | 保护临界区资源 | 任务同步/简单资源计数 | --- ### **6. 调试技巧** 1. **统计监控**: 使用`uxSemaphoreGetCount()`检查锁状态: ```c UBaseType_t count = uxSemaphoreGetCount(xMutex); // 0表示被占用,1表示空闲 ``` 2. **死锁检测**: 启用FreeRTOS的`configUSE_MUTEXES``configCHECK_FOR_STACK_OVERFLOW`配置项 3. **Trace可视化**: 使用SystemView或Tracealyzer工具实时观察锁的获取/释放顺序 --- ### **7. 常见错误示例** **错误1:跨任务释放锁** ```c void Task1() { xSemaphoreTake(xMutex, portMAX_DELAY); // Task1获取锁 } void Task2() { xSemaphoreGive(xMutex); // 错误!Task2试图释放Task1的锁 } ``` **结果**:触发`configASSERT()`断言失败(若启用) **错误2:忘记释放锁** ```c void FaultyTask() { xSemaphoreTake(xMutex, portMAX_DELAY); if (error_condition) return; // 直接返回未释放锁 xSemaphoreGive(xMutex); } ``` **解决方案**:使用`do{...}while(0)`结构确保释放: ```c xSemaphoreTake(xMutex, portMAX_DELAY); do { if (error) break; // 正常操作 } while(0); xSemaphoreGive(xMutex); ``` --- **总结**:FreeRTOS互斥锁通过优先级继承机制优化了资源保护,使用时需严格遵循"获取-操作-释放"模式,并根据需求选择基础锁或递归锁。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值