我想在 Windows 上编写一个 C++ 程序(但最好支持跨平台),其中我有两个基于优先级抢占式调度的线程- 这就像一个中断行为(当中断发生时,主线程在任何地方暂停只有当中断线程重新进入睡眠状态时,主线程才会从暂停的地方恢复)。
这些是线程:
- 线程 T_main
- 线程 T_interrupt。
T_main 一直在 while 循环中运行。T_interrupt 应该每秒执行一次,并且它的执行速度非常快。
T_main 中的代码相当大(数千行代码)。
它必须非常准确。
我希望当 T_interrupt 线程运行的时候,它会被优先考虑,这样它就可以不间断地运行,直到它完成,然后线程 T_main 才会从它暂停的地方恢复。
如果您想知道我要做什么,那么这里有一个基本解释:基本上,我正在运行我的嵌入式项目的模拟。我模拟了我的整个硬件,我想在 PC 上的模拟器上运行我的应用程序。目的是测试我的应用程序的逻辑实现。编译器差异和其他缺陷被考虑在内。对我来说至关重要的是能够模拟我的 MCU 上存在的基于 1 秒滴答定时器的中断。我发现很难模拟这种行为,因为线程调度似乎是合作的而不是抢先的。
我尝试使用优先级和设置调度方法,例如循环SCHED_RR
或 FIFO SCHED_FIFO
,但在所有情况下,调度实现仍然是协作的,而不是抢占式的。
这是我的代码:
#include <iostream>
#include <thread>
#include <pthread.h>
#include <string>
using namespace std;
void MainApplicationFunc(void)
{
// Infinite loop in which the app is running
while(1)
{
MainProgram();
}
}
void TickTimerInterruptFunc()
{
while(1)
{
TickTimer();
std::this_thread::sleep_for(1s);
}
}
void setScheduling(std::thread &th, int policy, int priority)
{
sched_param sch_params;
sch_params.sched_priority = priority;
if(pthread_setschedparam(th.native_handle(), policy, &sch_params))
{
std::cerr << "Failed to set Thread scheduling" << std::endl;
}
}
int main()
{
std::thread T_interrupt(TickTimerInterruptFunc);
setScheduling(T_interrupt, SCHED_FIFO, 1);
std::thread T_main(MainApplicationFunc);
setScheduling(T_main, SCHED_FIFO, 20);
T_main.join();
T_interrupt.join();
}