|
信号量
信号量是一种轻型的用于解决线程间同步问题的内核对象,线程可以获取或释放它,从而达到同步或互斥的目的。信号量就像一把钥匙,把一段临界区给锁住,只允许有钥匙的线程进行访问:线程拿到了钥匙,才允许它进入临界区;而离开后把钥匙传递给排队在后面的等待线程,让后续线程依次进入临界区。
信号量工作示意图如图 信号量工作示意图 所示,每个信号量对象都有一个信号量值和一个线程等待队列,信号量的值对应了信号量对象的实例数目、资源数目,假如信号量值为5,则表示共有5个信号量实例(资源)可以被使用,当信号量实例数目为零时,再申请该信号量的线程就会被挂起在该信号量的等待队列上,等待可用的信号量实例(资源)。
RT-Thread信号量相关接口
初始化信号量
对于静态信号量对象,它的内存空间在编译时期就被编译器分配出来,放在数据段或ZI段上,此时使用信号量就不再需要使用rt_sem_create接口来创建它,而只需在使用前对它进行初始化即可。初始化信号量对象可使用下面的函数接口:
- rt_err_t rt_sem_init (rt_sem_t sem, const char* name, rt_uint32_t value, rt_uint8_t flag);
复制代码
当调用这个函数时,系统将对这个semaphore对象进行初始化,然后初始化IPC对象以及与semaphore相关的部分。在初始化信号量指定的参数中,信号量标志参数决定了当信号量不可用时,多个线程等待的方式。当选择FIFO方式时,那么等待线程队列将按照先进先出的方式排队,先进入的线程将先获得等待的信号量;当选择PRIO(优先级等待)方式时,等待线程队列将按照优先级进行排队,优先级高的等待线程将先获得等待的信号量。
参数 描述
sem 信号量对象的句柄;
name 信号量名称;
value 信号量初始值;
flag 信号量标志。
- #define RT_IPC_FLAG_FIFO 0x00 /* IPC参数采用FIFO方式*/
- #define RT_IPC_FLAG_PRIO 0x01 /* IPC参数采用优先级方式*/
复制代码
函数返回
RT_EOK
获取信号量
线程通过获取信号量来获得信号量资源实例,当信号量值大于零时,线程将获得信号量,并且相应的信号量值都会减1,获取信号量使用下面的函数接口:
- rt_err_t rt_sem_take (rt_sem_t sem, rt_int32_t time);
复制代码
在调用这个函数时,如果信号量的值等于零,那么说明当前信号量资源实例不可用,申请该信号量的线程将根据time参数的情况选择直接返回、或挂起等待一段时间、或永久等待,直到其他线程或中断释放该信号量。如果在参数time指定的时间内依然得不到信号量,线程将超时返回,返回值是-RT_ETIMEOUT。
函数参数
参数 描述
sem 信号量对象的句柄;
time 指定的等待时间,单位是操作系统时钟节拍(OS Tick)。
函数返回
成功获得信号量返回RT_EOK;超时依然未获得信号量返回-RT_ETIMEOUT;其他错误返回-RT_ERROR。
无等待获取信号量
当用户不想在申请的信号量上挂起线程进行等待时,可以使用无等待方式获取信号量,无等待获取信号量使用下面的函数接口:
- rt_err_t rt_sem_trytake(rt_sem_t sem);
复制代码
这个函数与rt_sem_take(sem, 0) 的作用相同,即当线程申请的信号量资源实例不可用的时候,它不会等待在该信号量上,而是直接返回-RT_ETIMEOUT。
函数参数
参数 描述
sem 信号量对象的句柄。
函数返回
成功获取信号量返回RT_EOK;否则返回RT_ETIMEOUT。
释放信号量
当线程完成资源的访问后,应尽快释放它持有的信号量,使得其他线程能获得该信号量。释放信号量使用下面的函数接口:
- rt_err_t rt_sem_release(rt_sem_t sem);
复制代码
当信号量的值等于零时,并且有线程等待这个信号量时,将唤醒等待在该信号量线程队列中的第一个线程,由它获取信号量。否则将把信号量的值加一。
函数参数
参数 描述
sem 信号量对象的句柄。
函数返回
RT_EOK
下面在机智云gokit开发板上演示如何初始化一个信号量,并使用信号量来进行任务同步的例子,程序中创建2个线程,低优先级线程1发送信号量,高优先级线程2等待信号量后翻转Gokit上的红色LED。
- /**
- ****************************************************
- * File Name : main.c
- * Description : Main program body
- ****************************************************
- ** This notice applies to any and all portions of this file
- * that are not between comment pairs USER CODE BEGIN and
- * USER CODE END. Other portions of this file, whether
- * inserted by the user or by software development tools
- * are owned by their respective copyright owners.
- *
- * COPYRIGHT(c) 2017 STMicroelectronics
- *
- * Redistribution and use in source and binary forms, with or without modification,
- * are permitted provided that the following conditions are met:
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. Neither the name of STMicroelectronics nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- ****************************************************
- */
- /* Includes ------------------------------------------------------------------*/
- #include "main.h"
- #include "STM32f1xx_hal.h"
- #include "usart.h"
- #include "gpio.h"
- /* USER CODE BEGIN Includes */
- #include "rtthread.h"
- #include "string.h"
- /* USER CODE END Includes */
- /* Private variables ---------------------------------------------------------*/
- /* USER CODE BEGIN PV */
- /* Private variables ---------------------------------------------------------*/
- /* USER CODE END PV */
- /* Private function prototypes -----------------------------------------------*/
- void SystemClock_Config(void);
- /* USER CODE BEGIN PFP */
- /* Private function prototypes -----------------------------------------------*/
- /* USER CODE END PFP */
- /* USER CODE BEGIN 0 */
- //重映射串口1到rt_kprintf
- void rt_hw_console_output(const char *str)
- {
- /* empty console output */
- char aa='\r';
- rt_enter_critical();
- while(*str!='\0')
- {
- if(*str=='\n')
- {
- HAL_UART_Transmit(&huart1, (uint8_t *)&aa, 1, 10);
- }
- HAL_UART_Transmit(&huart1, (uint8_t *)(str++), 1, 10);
- }
-
- rt_exit_critical();
- }
- void rt_hw_us_delay(int us)
- {
- rt_uint32_t delta;
- /* 获得延时经过的tick数 */
- us = us * (SysTick->LOAD/(1000000/RT_TICK_PER_SECOND));
- /* 获得当前时间 */
- delta = SysTick->VAL;
- /* 循环获得当前时间,直到达到指定的时间后退出循环 */
- while (delta - SysTick->VAL< us);
- }
- void rt_hw_ms_delay(int ms)
- {
- int i=0,j=0;
- for(j=0;j<ms;j++)
- {
- for (i=0;i<2;i++)
- rt_hw_us_delay(500);
- }
- }
- /*
- * 程序清单:创建2个线程,低优先级线程1发送信号量,高优先级线程2等待信号量后翻转Gokit上的红色LED。
- */
- /* 指向线程控制块的指针 */
- static rt_thread_t tid1 = RT_NULL;
- static rt_thread_t tid2 = RT_NULL;
- /* 信号量控制块 */
- struct rt_semaphore sem;
- /* 线程1入口 */
- static void thread1_entry(void* parameter)
- {
- while (1)
- {
- rt_kprintf("low thread release a sem.\n");
- rt_sem_release(&sem);
- rt_thread_delay(1000);
- }
- }
- /* 线程2入口 */
- static void thread2_entry(void* parameter)
- {
- while (1)
- {
- rt_sem_take(&sem, RT_WAITING_FOREVER);//永久等待信号量
- rt_kprintf("high thread take sem.\n");
- LED1_Toggle();
- LED2_Toggle();
- LED3_Toggle();
- LED4_Toggle();
- }
- }
- /* USER CODE END 0 */
- int main(void)
- {
- /* USER CODE BEGIN 1 */
- /* USER CODE END 1 */
- /* MCU Configuration----------------------------------------------------------*/
- // /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
- // HAL_Init();
- // /* USER CODE BEGIN Init */
- // /* USER CODE END Init */
- // /* Configure the system clock */
- // SystemClock_Config();
- // /* USER CODE BEGIN SysInit */
- // /* USER CODE END SysInit */
- // /* Initialize all configured peripherals */
- // MX_GPIO_Init();
- // MX_USART1_UART_Init();
- /* USER CODE BEGIN 2 */
-
- /* 初始化信号量 */
- rt_sem_init(&sem , "sem", 0, RT_IPC_FLAG_FIFO);//初始化信号量
-
- /* 创建线程1 */
- tid1 = rt_thread_create("tid1",
- thread1_entry, /* 线程入口是thread1_entry */
- RT_NULL, /* 入口参数是RT_NULL */
- 512,
- 3, //优先级
- 20);
- if (tid1 != RT_NULL)
- rt_thread_startup(tid1);
- /* 创建线程2 */
- tid2 = rt_thread_create("tid2",
- thread2_entry,/* 线程入口是thread2_entry */
- RT_NULL, /* 入口参数是RT_NULL */
- 512,
- 2,//优先级
- 20);
- if (tid2 != RT_NULL)
- rt_thread_startup(tid2);
-
-
- printf("\r\n机智云 只为智能硬件而生\r\n");
- printf("Gizwits Smart Cloud for Smart Products\r\n");
- printf("链接|增值|开放|中立|安全|自有|自由|生态\r\n");
- printf("www.gizwits.com\r\n");
- printf("\r\nGokit RT-Thread Demo\r\n\r\n");
-
- return 0;
-
-
- /* USER CODE END 2 */
- /* Infinite loop */
- /* USER CODE BEGIN WHILE */
- // while (1)
- // {
- /* USER CODE END WHILE */
- /* USER CODE BEGIN 3 */
- //
- // }
- /* USER CODE END 3 */
- }
- /** System Clock Configuration
- */
- void SystemClock_Config(void)
- {
- RCC_OscInitTypeDef RCC_OscInitStruct;
- RCC_ClkInitTypeDef RCC_ClkInitStruct;
- /**Initializes the CPU, AHB and APB busses clocks
- */
- RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
- RCC_OscInitStruct.HSEState = RCC_HSE_ON;
- RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
- RCC_OscInitStruct.HSIState = RCC_HSI_ON;
- RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
- RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
- RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
- if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
- {
- _Error_Handler(__FILE__, __LINE__);
- }
- /**Initializes the CPU, AHB and APB busses clocks
- */
- RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
- |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
- RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
- RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
- RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
- RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
- if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
- {
- _Error_Handler(__FILE__, __LINE__);
- }
- /**Configure the Systick interrupt time
- */
- HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);
- /**Configure the Systick
- */
- HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
- /* SysTick_IRQn interrupt configuration */
- HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
- }
- /* USER CODE BEGIN 4 */
- /* USER CODE END 4 */
- /**
- * @brief This function is executed in case of error occurrence.
- * @param None
- * @retval None
- */
- void _Error_Handler(char * file, int line)
- {
- /* USER CODE BEGIN Error_Handler_Debug */
- /* User can add his own implementation to report the HAL error return state */
- while(1)
- {
- }
- /* USER CODE END Error_Handler_Debug */
- }
- #ifdef USE_FULL_ASSERT
- /**
- * @brief Reports the name of the source file and the source line number
- * where the assert_param error has occurred.
- * @param file: pointer to the source file name
- * @param line: assert_param error line source number
- * @retval None
- */
- void assert_failed(uint8_t* file, uint32_t line)
- {
- /* USER CODE BEGIN 6 */
- /* User can add his own implementation to report the file name and line number,
- ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
- /* USER CODE END 6 */
- }
- #endif
- /**
- * @}
- */
- /**
- * @}
- */
- /**************** (C) COPYRIGHT STMicroelectronics ****END OF FILE***/
复制代码
串口助手现象如下:
每隔1s,LED翻转状态:
源码下载:
Gokit_RT-Thread.zip
(8.7 MB, 下载次数: 2, 售价: 1 金钱)
|
|