在 Linux 中,哪个选项更快:发布/解锁信号量/互斥体或创建新线程?

问题描述 投票:0回答:1

我有一个在 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(&not_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(&not_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;
}

预先感谢您的关注。

c linux multithreading pthreads real-time
1个回答
0
投票

阅读 glibc 源代码 表明,如果没有线程等待,互斥锁总是会更快,如果有线程,则将花费一个系统调用。从内核源来看,系统调用与克隆相比相当便宜。

© www.soinside.com 2019 - 2024. All rights reserved.