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