#include <rthw.h>
#include <rtthread.h>
#define THREAD_PRIORITY 20
#define THREAD_STACK_SIZE 512
#define THREAD_TIMESLICE 5
/* 同时访问的全局变量 */
static rt_uint32_t cnt = 0;
void thread_entry(void *parameter)
{
rt_uint32_t no;
rt_uint32_t level;
no = (rt_uint32_t) parameter;
while (1)
{
/*调度上锁*/
if(cnt < 10)
rt_enter_critical();
cnt += no;
if(cnt = 40)
/*调度解锁*/
rt_exit_critical();
rt_kprintf("protect thread[%d]'s counter is %d\n", no, cnt);
rt_thread_mdelay(no * 10);
}
}
/* 用户应用程序入口 */
int interrupt_sample(void)
{
rt_thread_t thread;
/* 创建t1线程 */
thread = rt_thread_create("thread1", thread_entry, (void *)10,
THREAD_STACK_SIZE,
THREAD_PRIORITY, THREAD_TIMESLICE);
if (thread != RT_NULL)
rt_thread_startup(thread);
/* 创建t2线程 */
thread = rt_thread_create("thread2", thread_entry, (void *)20,
THREAD_STACK_SIZE,
THREAD_PRIORITY, THREAD_TIMESLICE);
if (thread != RT_NULL)
rt_thread_startup(thread);
return 0;
}
/* 导出到 msh 命令列表中 */
MSH_CMD_EXPORT(interrupt_sample, interrupt sample);
此代码是实现0–40 线程1调度,40以后线程1 、2 共同调度
但现象是
问题在于
程序设计应该严谨
讲道理,结果应该是
10 10
10 20
10 30
10 40
20 60
10 70
10 80
20 100
。。。。
从整体上看,10的执行2次;20的执行1次
这个是没有问题的
实际上 10 40 应该被打印的,但是退出临界区后,线程就进行了调度,此时出cnt值为40;
调度之后,进入20的那个线程,cnt+20 = 60接着打印60
在之后线程2主动出让程序,由线程1执行,因为此时cnt = 60 ,所以打印60,再然后线程1主动出让,后面的就基本正常了
只是程序设计有问题
多线程对公共资源的保护;比如使用公共资源前打印,可能就不会出现这样的问题。
调度关闭分层次
如果前面进去了4关闭调度,应该已经是第4层了;你就是退出一次,仍然在第3层,仍会在临界区,不会调度,如果要实现退出
至少要保证,进去和出去的次数一样