如何在QNX上强制使用特定的线程序列?

时间:2013-01-04 15:05:51

标签: c++ multithreading semaphore qnx

我有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。所以我的问题是:这是否有效,是否有更好或内置的方法来做到这一点?

1 个答案:

答案 0 :(得分:1)

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

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

我将调度逻辑移动到一个公共点(可能传递线程类型,迭代次数,并发出信号)。

我将每个sem_post信号发出一个循环迭代请求。因此,如果您希望C运行3次,请致电sem_post 3次。

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

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

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

相关问题