Question

I have 3 threads: A, B and C and want to schedule the sequence A,B,B,C,C,C,B,B,A in C++ on the QNX real time operating system. My approach is to use semaphores and save the last executed thread (because B->C and 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);
}

Unfortunately i can't test my code because i don't have QNX installed. So my question: Will this work and is there a better or built in way to do this?

Was it helpful?

Solution

You are relying on threads started running immediately or something like that? There are definitely better ways to do this.

Your threads should wait on their semaphore before doing anything else.

I'd move the scheduling logic to one common spot (maybe pass in thread type, and number of iterations, and it sends out signals).

I'd have each sem_post signal a single loop iteration request. So if you want C to run 3 times, call sem_post 3 times.

I have no idea what you are doing with the first argument to pthread_create. Overwriting a function with thread data? Bad idea.

As this is C++, I'd wrap up the creation of threads into an object. And I'd pass in things like the semaphore to wait on in the void* arg.

I suspect you either need more experience writing multi-threaded code, or the ability to debug on a live platform, in order to succeed at your task.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top