2013-01-04 32 views
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測試我的代碼。所以我的問題是:這會工作,並有更好的或建立的方式來做到這一點?

+2

如果您想要順序操作,請使用任務隊列,並且根本不要使用線程(或單個使用者)。線程爲程序增加了相當大的複雜性,這對於具有異步執行的優勢來說很好。現在,拿走這個優勢似乎有點荒謬。在這種情況下,最好不要開始。 – Damon

+0

請注意,線程之間有幾個定義明確的同步點可以,而且通常是必需的。然而,這與你所問的完全不同。爲此,可以使用條件變量,信號量或障礙(根據情況)。 – Damon

回答

1

你是依靠線程立即開始運行或類似的東西?有絕對好的方法來做到這一點。

你的線程在做任何事情之前都應該先等待它們的信號量。我想將調度邏輯移動到一個公共點(可能傳入線程類型和迭代次數,併發出信號)。

我想每個sem_post信號一個循環迭代請求。所以如果你想讓C運行3次,請撥打sem_post 3次。

我不知道你在做什麼第一個參數pthread_create。用線程數據覆蓋函數?餿主意。

因爲這是C++,所以我將線程創建包裝到一個對象中。我會通過諸如信號量之類的東西來等待void*參數。

我懷疑你要麼需要更多的編寫多線程代碼的經驗,要麼需要在實時平臺上進行調試才能成功完成任務。

相關問題