1
我有3個線程:A,B和C,並且希望在QNX實時操作系統上用C++計劃序列A,B,B,C,C,C,B,B,A。 我的方法是使用信號量和保存最後執行的線程(因爲B-> C和B-> A):如何強制QNX上的特定線程序列?
#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測試我的代碼。所以我的問題是:這會工作,並有更好的或建立的方式來做到這一點?
如果您想要順序操作,請使用任務隊列,並且根本不要使用線程(或單個使用者)。線程爲程序增加了相當大的複雜性,這對於具有異步執行的優勢來說很好。現在,拿走這個優勢似乎有點荒謬。在這種情況下,最好不要開始。 – Damon
請注意,線程之間有幾個定義明確的同步點可以,而且通常是必需的。然而,這與你所問的完全不同。爲此,可以使用條件變量,信號量或障礙(根據情況)。 – Damon