收藏官网首页
查看: 10771|回复: 0

【一起来玩RTOS系列】之RT-Thread 信号量用于资源计数

321

主题

1054

帖子

4502

积分

论坛元老

Rank: 8Rank: 8

积分
4502
QQ
跳转到指定楼层
楼主
发表于 2017-12-2 12:39:09 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
校园创客福利
本帖最后由 bigfanofloT 于 2017-12-2 12:42 编辑


资源计数适合于线程间速度不匹配的场合,这个时候信号量可以做为前一线程工作完成的计数,而当调度到后一线程时,它可以以一种连续的方式一次处理数个事件。例如,生产者与消费者问题中,生产者可以对信号进行多次释放,而后消费者被调度到时能够一次处理多个资源。
注: 一般资源计数类型多是混合方式的线程间同步,因为对于单个的资源处理依然存在线程的多重访问,这就需要对一个单独的资源进行访问、处理,并进行锁方式的互斥操作。

生产者消费者问题(英语:Producer-consumer problem),也称有限缓冲问题(英语:Bounded-buffer problem),是一个多线程同步问题的经典案例。该问题描述了两个共享固定大小缓冲区的线程——即所谓的“生产者”和“消费者”——在实际运行时会发生的问题。生产者的主要作用是生成一定量的数据放到缓冲区中,然后重复此过程。与此同时,消费者也在缓冲区消耗这些数据。该问题的关键就是要保证生产者不会在缓冲区满时加入数据,消费者也不会在缓冲区中空时消耗数据。
解决办法
要解决该问题,就必须让生产者在缓冲区满时休眠(要么干脆就放弃数据),等到下次消费者消耗缓冲区中的数据的时候,生产者才能被唤醒,开始往缓冲区添加数据。同样,也可以让消费者在缓冲区空时进入休眠,等到生产者往缓冲区添加数据之后,再唤醒消费者。通常采用进程间通信的方法解决该问题,常用的方法有信号灯法等。如果解决方法不够完善,则容易出现死锁的情况。出现死锁时,两个线程都会陷入休眠,等待对方唤醒自己。该问题也能被推广到多个生产者和消费者的情形。

接下来在机智云gokit开发板上演示如何创建并使用信号量作为锁来进行资源的互斥访问,程序中semaphore是作为一种锁的形式存在,当要访问临界资源时,通过持有semaphore 的形式阻止其他线程进入。生产者线程负责生产产品,生产的产品放入缓冲区,当缓冲区满了时,生产者暂停生产,等待消费者消费缓冲区中的产品再重新启动。生产者生产产品前,需要确保缓冲区不满。消费者线程负责消费缓冲区中的产品,当缓冲区为空时,消费者暂停消费,等生产者向缓冲区中放入新的产品后再重新启动。消费者消费产品之前,需要确保缓冲区不为空。

  1. /**
  2.   ***********************************
  3.   * File Name          : main.c
  4.   * Description        : Main program body
  5.   ***********************************
  6.   ** This notice applies to any and all portions of this file
  7.   * that are not between comment pairs USER CODE BEGIN and
  8.   * USER CODE END. Other portions of this file, whether
  9.   * inserted by the user or by software development tools
  10.   * are owned by their respective copyright owners.
  11.   *
  12.   * COPYRIGHT(c) 2017 STMicroelectronics
  13.   *
  14.   * Redistribution and use in source and binary forms, with or without modification,
  15.   * are permitted provided that the following conditions are met:
  16.   *   1. Redistributions of source code must retain the above copyright notice,
  17.   *      this list of conditions and the following disclaimer.
  18.   *   2. Redistributions in binary form must reproduce the above copyright notice,
  19.   *      this list of conditions and the following disclaimer in the documentation
  20.   *      and/or other materials provided with the distribution.
  21.   *   3. Neither the name of STMicroelectronics nor the names of its contributors
  22.   *      may be used to endorse or promote products derived from this software
  23.   *      without specific prior written permission.
  24.   *
  25.   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  26.   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  27.   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  28.   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  29.   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  30.   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  31.   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  32.   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  33.   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  34.   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  35.   *
  36.   ***********************************
  37.   */
  38. /* Includes ------------------------------------------------------------------*/
  39. #include "main.h"
  40. #include "STM32f1xx_hal.h"
  41. #include "usart.h"
  42. #include "gpio.h"

  43. /* USER CODE BEGIN Includes */
  44. #include "rtthread.h"
  45. #include "string.h"
  46. /* USER CODE END Includes */

  47. /* Private variables ---------------------------------------------------------*/

  48. /* USER CODE BEGIN PV */
  49. /* Private variables ---------------------------------------------------------*/

  50. /* USER CODE END PV */

  51. /* Private function prototypes -----------------------------------------------*/
  52. void SystemClock_Config(void);

  53. /* USER CODE BEGIN PFP */
  54. /* Private function prototypes -----------------------------------------------*/

  55. /* USER CODE END PFP */

  56. /* USER CODE BEGIN 0 */
  57. //重映射串口1到rt_kprintf
  58. void rt_hw_console_output(const char *str)
  59. {
  60.     /* empty console output */
  61.         char aa='\r';
  62.           rt_enter_critical();

  63.                 while(*str!='\0')
  64.                 {
  65.                         if(*str=='\n')
  66.                         {
  67.                                 HAL_UART_Transmit(&huart1, (uint8_t *)&aa, 1, 10);
  68.                         }
  69.                                 HAL_UART_Transmit(&huart1, (uint8_t *)(str++), 1, 10);
  70.                 }
  71.                
  72.                 rt_exit_critical();
  73. }

  74. void rt_hw_us_delay(int us)
  75. {
  76.     rt_uint32_t delta;

  77.     /* 获得延时经过的tick数 */
  78.     us = us * (SysTick->LOAD/(1000000/RT_TICK_PER_SECOND));

  79.     /* 获得当前时间 */
  80.     delta = SysTick->VAL;

  81.     /* 循环获得当前时间,直到达到指定的时间后退出循环 */
  82.     while (delta - SysTick->VAL< us);
  83. }

  84. void rt_hw_ms_delay(int ms)
  85. {
  86.         int i=0,j=0;
  87.         for(j=0;j<ms;j++)
  88.         {
  89.                 for (i=0;i<2;i++)
  90.                 rt_hw_us_delay(500);
  91.         }
  92. }

  93. /*
  94. * 程序清单:生产者消费者例子
  95. *
  96. * 这个例子中将创建两个线程用于实现生产者消费者问题
  97. */
  98. #include <rtthread.h>

  99. /* 定义最大5个元素能够被产生 */
  100. #define MAXSEM     5

  101. /* 用于放置生产的整数数组 */
  102. rt_uint32_t array[MAXSEM];
  103. /* 指向生产者、消费者在array数组中的读写位置 */
  104. static rt_uint32_t set, get;

  105. /* 指向线程控制块的指针 */
  106. static rt_thread_t producer_tid = RT_NULL;
  107. static rt_thread_t consumer_tid = RT_NULL;

  108. struct rt_semaphore sem_lock;
  109. struct rt_semaphore sem_empty, sem_full;

  110. /* 生产者线程入口 */
  111. void producer_thread_entry(void* parameter)
  112. {
  113.     rt_int32_t cnt = 0;

  114.     /* 运行100次 */
  115.     while( cnt < 100)
  116.     {
  117.         /* 获取一个空位 */
  118.         rt_sem_take(&sem_empty, RT_WAITING_FOREVER);

  119.         /* 修改array内容,上锁 */
  120.         rt_sem_take(&sem_lock, RT_WAITING_FOREVER);
  121.         array[set%MAXSEM] = cnt + 1;
  122.         rt_kprintf("the producer generates a number: %d\n",
  123.             array[set%MAXSEM]);
  124.         set++;
  125.         rt_sem_release(&sem_lock);

  126.         /* 发布一个满位 */
  127.         rt_sem_release(&sem_full);
  128.         cnt++;

  129.         /* 暂停一段时间 */
  130.         rt_thread_delay(50);
  131.     }

  132.     rt_kprintf("the producer exit!\n");
  133. }

  134. /* 消费者线程入口 */
  135. void consumer0_thread_entry(void* parameter)
  136. {
  137.     rt_uint32_t no;
  138.     rt_uint32_t sum = 0;

  139.     /* 第0个线程 */
  140.     no = 0;

  141.     while(1)
  142.     {
  143.         /* 获取一个满位 */
  144.         rt_sem_take(&sem_full, RT_WAITING_FOREVER);

  145.         /* 临界区,上锁进行操作 */
  146.         rt_sem_take(&sem_lock, RT_WAITING_FOREVER);
  147.         sum += array[get%MAXSEM];
  148.         rt_kprintf("the consumer[%d] get a number:%d\n", no, array[get%MAXSEM]);
  149.         get++;
  150.         rt_sem_release(&sem_lock);

  151.         /* 释放一个空位 */
  152.         rt_sem_release(&sem_empty);

  153.         /* 生产者生产到100个数目,停止,消费者线程相应停止 */
  154.         if (get == 100) break;

  155.         /* 暂停一小会时间 */
  156.         rt_thread_delay(10);
  157.     }

  158.     rt_kprintf("the consumer[%d] sum is %d \n ", no, sum);
  159.     rt_kprintf("the consumer[%d] exit!\n",no);
  160. }
  161. /* 消费者线程入口 */
  162. void consumer1_thread_entry(void* parameter)
  163. {
  164.     rt_uint32_t no;
  165.     rt_uint32_t sum = 0;

  166.     /* 第1个线程 */
  167.     no = 1;

  168.     while(1)
  169.     {
  170.         /* 获取一个满位 */
  171.         rt_sem_take(&sem_full, RT_WAITING_FOREVER);

  172.         /* 临界区,上锁进行操作 */
  173.         rt_sem_take(&sem_lock, RT_WAITING_FOREVER);
  174.         sum += array[get%MAXSEM];
  175.         rt_kprintf("the consumer[%d] get a number:%d\n", no, array[get%MAXSEM]);
  176.         get++;
  177.         rt_sem_release(&sem_lock);

  178.         /* 释放一个空位 */
  179.         rt_sem_release(&sem_empty);

  180.         /* 生产者生产到100个数目,停止,消费者线程相应停止 */
  181.         if (get == 100) break;

  182.         /* 暂停一小会时间 */
  183.         rt_thread_delay(10);
  184.     }

  185.     rt_kprintf("the consumer[%d] sum is %d \n ", no, sum);
  186.     rt_kprintf("the consumer[%d] exit!\n",no);
  187. }
  188. /* 消费者线程入口 */
  189. void consumer2_thread_entry(void* parameter)
  190. {
  191.     rt_uint32_t no;
  192.     rt_uint32_t sum = 0;

  193.     /* 第2个线程 */
  194.     no = 2;

  195.     while(1)
  196.     {
  197.         /* 获取一个满位 */
  198.         rt_sem_take(&sem_full, RT_WAITING_FOREVER);

  199.         /* 临界区,上锁进行操作 */
  200.         rt_sem_take(&sem_lock, RT_WAITING_FOREVER);
  201.         sum += array[get%MAXSEM];
  202.         rt_kprintf("the consumer[%d] get a number:%d\n", no, array[get%MAXSEM]);
  203.         get++;
  204.         rt_sem_release(&sem_lock);

  205.         /* 释放一个空位 */
  206.         rt_sem_release(&sem_empty);

  207.         /* 生产者生产到100个数目,停止,消费者线程相应停止 */
  208.         if (get == 100) break;

  209.         /* 暂停一小会时间 */
  210.         rt_thread_delay(10);
  211.     }

  212.     rt_kprintf("the consumer[%d] sum is %d \n ", no, sum);
  213.     rt_kprintf("the consumer[%d] exit!\n",no);
  214. }
  215. int semaphore_producer_consumer_init()
  216. {
  217.     /* 初始化3个信号量 */
  218.     rt_sem_init(&sem_lock , "lock",   1,    RT_IPC_FLAG_FIFO);
  219.     rt_sem_init(&sem_empty,"empty", MAXSEM, RT_IPC_FLAG_FIFO);
  220.     rt_sem_init(&sem_full , "full",   0,   RT_IPC_FLAG_FIFO);

  221.     /* 创建线程1 */
  222.     producer_tid = rt_thread_create("producer",
  223.         producer_thread_entry, /* 线程入口是producer_thread_entry */
  224.         RT_NULL, /* 入口参数是RT_NULL */
  225.         512, 1, 20);
  226.     if (producer_tid != RT_NULL)
  227.         rt_thread_startup(producer_tid);
  228.                
  229.     /* 创建线程2 */
  230.     consumer_tid = rt_thread_create("consumer0",
  231.        consumer0_thread_entry,/* 线程入口是consumer_thread_entry */
  232.         RT_NULL, /* 入口参数是RT_NULL */
  233.         512, 3, 20);
  234.     if (consumer_tid != RT_NULL)
  235.         rt_thread_startup(consumer_tid);
  236.                
  237.                     /* 创建线程3 */
  238.     consumer_tid = rt_thread_create("consumer1",
  239.        consumer1_thread_entry,/* 线程入口是consumer_thread_entry */
  240.         RT_NULL, /* 入口参数是RT_NULL */
  241.         512, 3, 20);
  242.     if (consumer_tid != RT_NULL)
  243.         rt_thread_startup(consumer_tid);
  244.                
  245.                                     /* 创建线程4 */
  246.     consumer_tid = rt_thread_create("consumer1",
  247.        consumer2_thread_entry,/* 线程入口是consumer_thread_entry */
  248.         RT_NULL, /* 入口参数是RT_NULL */
  249.         512, 3, 20);
  250.     if (consumer_tid != RT_NULL)
  251.         rt_thread_startup(consumer_tid);

  252.     return 0;
  253. }


  254. /* USER CODE END 0 */

  255. int main(void)
  256. {

  257.   /* USER CODE BEGIN 1 */

  258.   /* USER CODE END 1 */

  259.   /* MCU Configuration----------------------------------------------------------*/

  260. //  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  261. //  HAL_Init();

  262. //  /* USER CODE BEGIN Init */

  263. //  /* USER CODE END Init */

  264. //  /* Configure the system clock */
  265. //  SystemClock_Config();

  266. //  /* USER CODE BEGIN SysInit */

  267. //  /* USER CODE END SysInit */

  268. //  /* Initialize all configured peripherals */
  269. //  MX_GPIO_Init();
  270. //  MX_USART1_UART_Init();

  271.   /* USER CODE BEGIN 2 */
  272.         
  273. semaphore_producer_consumer_init();
  274.         
  275.         
  276.         printf("\r\n机智云  只为智能硬件而生\r\n");
  277.         printf("Gizwits Smart Cloud for Smart Products\r\n");
  278.         printf("链接|增值|开放|中立|安全|自有|自由|生态\r\n");
  279.         printf("www.gizwits.com\r\n");
  280.         printf("\r\nGokit RT-Thread Demo\r\n\r\n");
  281.         
  282.         return 0;
  283.         
  284.         


  285.   /* USER CODE END 2 */

  286.   /* Infinite loop */
  287.   /* USER CODE BEGIN WHILE */
  288. //  while (1)
  289. //  {
  290.   /* USER CODE END WHILE */

  291.   /* USER CODE BEGIN 3 */
  292. //               
  293. //  }
  294.   /* USER CODE END 3 */

  295. }

  296. /** System Clock Configuration
  297. */
  298. void SystemClock_Config(void)
  299. {

  300.   RCC_OscInitTypeDef RCC_OscInitStruct;
  301.   RCC_ClkInitTypeDef RCC_ClkInitStruct;

  302.     /**Initializes the CPU, AHB and APB busses clocks
  303.     */
  304.   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  305.   RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  306.   RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  307.   RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  308.   RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  309.   RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  310.   RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  311.   if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  312.   {
  313.     _Error_Handler(__FILE__, __LINE__);
  314.   }

  315.     /**Initializes the CPU, AHB and APB busses clocks
  316.     */
  317.   RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
  318.                               |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  319.   RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  320.   RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  321.   RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  322.   RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  323.   if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  324.   {
  325.     _Error_Handler(__FILE__, __LINE__);
  326.   }

  327.     /**Configure the Systick interrupt time
  328.     */
  329.   HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);

  330.     /**Configure the Systick
  331.     */
  332.   HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);

  333.   /* SysTick_IRQn interrupt configuration */
  334.   HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
  335. }

  336. /* USER CODE BEGIN 4 */

  337. /* USER CODE END 4 */

  338. /**
  339.   * @brief  This function is executed in case of error occurrence.
  340.   * @param  None
  341.   * @retval None
  342.   */
  343. void _Error_Handler(char * file, int line)
  344. {
  345.   /* USER CODE BEGIN Error_Handler_Debug */
  346.   /* User can add his own implementation to report the HAL error return state */
  347.   while(1)
  348.   {
  349.   }
  350.   /* USER CODE END Error_Handler_Debug */
  351. }

  352. #ifdef USE_FULL_ASSERT

  353. /**
  354.    * @brief Reports the name of the source file and the source line number
  355.    * where the assert_param error has occurred.
  356.    * @param file: pointer to the source file name
  357.    * @param line: assert_param error line source number
  358.    * @retval None
  359.    */
  360. void assert_failed(uint8_t* file, uint32_t line)
  361. {
  362.   /* USER CODE BEGIN 6 */
  363.   /* User can add his own implementation to report the file name and line number,
  364.     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  365.   /* USER CODE END 6 */

  366. }

  367. #endif

  368. /**
  369.   * @}
  370.   */

  371. /**
  372.   * @}
  373. */

  374. /*********** (C) COPYRIGHT STMicroelectronics ***END OF FILE**/
复制代码

串口打印信息如下:


源码下载:
Gokit_RT-Thread.zip (8.7 MB, 下载次数: 2, 售价: 1 金钱)

1、机智云QQ群:G1群:104975951 G2群:491509598 G3群:287087942
机智云爱好者-APP开发群: 599735135
QQ群目前非常活跃,欢迎大家参与进来,交流,讨论,答疑,解惑~~
2、机智云微信公众号: 机智云 gizwits、 机智云智能宠物屋go-iot
关注机智云Gizwits官方公众号随时掌握最新资讯和活动信息
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

加入Q群 返回顶部

版权与免责声明 © 2006-2024 Gizwits IoT Technology Co., Ltd. ( 粤ICP备11090211号 )

快速回复 返回顶部 返回列表