rsoc/Day1/mutex_sample.c

95 lines
2.6 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* 程序清单:互斥锁例程
*
* 互斥锁是一种保护共享资源的方法。当一个线程拥有互斥锁的时候,
* 可以保护共享资源不被其他线程破坏。线程1对2个number分别进行加1操作
* 线程2也会对2个number分别进行加1操作。使用互斥量保证2个number值保持一致
*/
#include <rtthread.h>
#define THREAD_PRIORITY 8
#define THREAD_TIMESLICE 5
/* 指向互斥量的指针 */
static rt_mutex_t dynamic_mutex = RT_NULL;
static rt_uint8_t number1, number2 = 0;
static char thread1_stack[1024];
static struct rt_thread thread1;
static void rt_thread_entry1(void *parameter)
{
while (1)
{
/* 线程1获取到互斥量后先后对number1、number2进行加1操作然后释放互斥量 */
rt_mutex_take(dynamic_mutex, RT_WAITING_FOREVER);
number1++;
rt_thread_mdelay(10);
number2++;
rt_mutex_release(dynamic_mutex);
}
}
static char thread2_stack[1024];
static struct rt_thread thread2;
static void rt_thread_entry2(void *parameter)
{
while (1)
{
/* 线程2获取到互斥量后检查number1、number2的值是否相同相同则表示mutex起到了锁的作用 */
rt_mutex_take(dynamic_mutex, RT_WAITING_FOREVER);
if (number1 != number2)
{
rt_kprintf("not protect.number1 = %d, mumber2 = %d \n", number1, number2);
}
else
{
rt_kprintf("mutex protect ,number1 = mumber2 is %d\n", number1);
}
number1++;
number2++;
rt_mutex_release(dynamic_mutex);
if (number1 >= 50)
return;
}
}
/* 互斥量示例的初始化 */
int mutex_sample(void)
{
/* 创建一个动态互斥量 */
dynamic_mutex = rt_mutex_create("dmutex", RT_IPC_FLAG_PRIO);
if (dynamic_mutex == RT_NULL)
{
rt_kprintf("create dynamic mutex failed.\n");
return -1;
}
rt_thread_init(&thread1,
"thread1",
rt_thread_entry1,
RT_NULL,
&thread1_stack[0],
sizeof(thread1_stack),
THREAD_PRIORITY, THREAD_TIMESLICE);
rt_thread_startup(&thread1);
rt_thread_init(&thread2,
"thread2",
rt_thread_entry2,
RT_NULL,
&thread2_stack[0],
sizeof(thread2_stack),
THREAD_PRIORITY - 1, THREAD_TIMESLICE);
rt_thread_startup(&thread2);
return 0;
}
/* 导出到 msh 命令列表中 */
MSH_CMD_EXPORT(mutex_sample, mutex sample);