1

我有 3 个线程:A、B 和 C,并且想在 QNX 实时操作系统上用 C++ 调度序列 A、B、B、C、C、C、B、B、A。我的方法是使用信号量并保存最后执行的线程(因为 B->C 和 B->A):

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
/*semaphores*/
sem_t sa = 1;
sem_t sb = 0;
sem_t sc = 0;

char last;         //remember the last processed thread


void* threadA (void* a) 
{
    while(1) 
    {
        sem_wait(&sa);          //p(sa)
        printf("threadA \n");   //threads function
        last = 'A';             //mark A as last processed
        sem_post(&sb);          //v(sb)
    }
}

void* threadB (void* a) 
{
    int c = 1;
    while(1) 
    {
        printf("threadB\n");
        if (c == 2)
        {
            sem_wait(&sb);
            c = 1;
            if (last == 'A')
            {
                last = 'B';
                sem_post(&sc);    
            }
            if (last == 'C')
            {
                last = 'B';
                sem_post(&sb)   
            }
        }
        c++;
    }
}

void* threadC (void* a) 
{
    int c = 1;
    while(1) 
    {
        printf("threadC \n");
        if (c == 3)
        {
            sem_wait(&sc);
            c = 1;
            last = 'C';
            sem_post(&sb);
        }
        c++;
    }
}

int main() 
{
    pthread_create (&threadA, NULL, threadA, NULL);
    pthread_create (&threadB, NULL, threadB, NULL);
    pthread_create (&threadC, NULL, threadC, NULL);
}

不幸的是,我无法测试我的代码,因为我没有安装 QNX。所以我的问题是:这会起作用吗?是否有更好的或内置的方法来做到这一点?

4

1 回答 1

1

您依赖于立即开始运行的线程或类似的东西吗?肯定有更好的方法来做到这一点。

您的线程应该在执行其他任何操作之前等待它们的信号量。

我会将调度逻辑移到一个公共位置(可能传入线程类型和迭代次数,然后发出信号)。

我会让每个sem_post信号都有一个循环迭代请求。所以如果你想C运行 3 次,调用sem_post3 次。

我不知道你在用第一个参数做什么pthread_create。用线程数据覆盖函数?馊主意。

由于这是 C++,我会将线程的创建封装到一个对象中。我会传递信号量之类的东西以在void*arg 中等待。

我怀疑您要么需要更多编写多线程代码的经验,要么需要在实时平台上进行调试,才能成功完成任务。

于 2013-01-04T15:44:58.753 回答