我有一个在 Linux 中运行的应用程序。它有一个用于实时控制的线程,这意味着该线程必须定期运行(周期约为 200 微秒),并且必须在已知的时间限制内提供输出。实时控制的线程具有抢占式调度的属性,目前运行良好。它运行在Raspberry Pi 3上,内存消耗非常低,所以内存不是问题,最大的担忧是CPU使用率。
在某些条件下,实时线程必须触发另一个任务的执行。虽然这个其他任务是 CPU 密集型的,但它不是实时任务,因此不需要以抢占式调度运行。
我的问题是:在以下选项中,是否有任何选项在实时线程上消耗的 CPU 时间显着减少?为什么?有没有更有效的解决方案来解决这个问题?
选项 A)每当必须执行非实时任务时,使用 pthread_create 函数为非实时任务创建一个新线程。
选项 B)仅为非实时任务创建一个线程一次,并使其等待由实时线程解锁/发布的互斥体/信号量。
选项 A 的示例:
void*
not_real_time_thread(void* args)
{
// do non-real-time things
return (void*) EXIT_SUCCESS;
}
void*
real_time_thread(void* args)
{
sem_t sync;
sem_init(&sync, 0, 0);
int end_event=0;
int running=1;
int trigger_other_task = 0;
pthread_t not_real_time_thread_handle;
pthread_attr_t thread_attrs; // Thread attributes
// init thread_attrs properly
// Real-time section
while(running)
{
// do real time things
if(trigger_other_task)
{
pthread_create(¬_real_time_thread_handle, &thread_attrs, not_real_time_thread, NULL);
}
if(end_event)
{
running=0;
}
}
sem_destroy(&sync);
return (void*) EXIT_SUCCESS;
}
选项 B 的示例:
int g_running;
sem_t g_semaphore;
void*
not_real_time_thread(void* args)
{
while(g_running)
{
sem_wait(&g_semaphore);
// do non-real-time things
}
return (void*) EXIT_SUCCESS;
}
void*
real_time_thread(void* args)
{
sem_t sync;
sem_init(&sync, 0, 0);
int end_event=0;
g_running=1;
int trigger_other_task = 0;
sem_init(&g_semaphore, 0, 0);
pthread_t not_real_time_thread_handle;
pthread_attr_t thread_attrs; // Thread attributes
// init thread_attrs properly
pthread_create(¬_real_time_thread_handle, &thread_attrs, not_real_time_thread, NULL);
// Real-time section
while(g_running)
{
// do real time things
if(trigger_other_task)
{
sem_post(&g_semaphore);
}
if(end_event)
{
g_running=0;
}
}
sem_destroy(&sync);
int thread_result=0;
pthread_join(not_real_time_thread_handle, (void*) &thread_result;
sem_destroy(semaphore);
return (void*) EXIT_SUCCESS;
}
预先感谢您的关注。