2015-08-25 26 views
-2

我想創建一個給定的函數的4個實例,但遇到問題如何調用的函數知道哪個線程調用它。調用相同的函數時線程的問題

這是在我的頭文件:

// GPIO PINS stored within structs, for each sonic range finder. 
typedef struct sonicPins { 
    // front left pins. 
    int trig1; 
    int echo1; 
    // front right pins. 
    int trig2; 
    int echo2; 
    // rear left pins. 
    int trig3; 
    int echo3; 
    // rear right pins. 
    int trig4; 
    int echo4; 
} args; 

void* setup(void *pinsPtr); 
extern int threadFunc(); 

這是我的C文件中。

int threadFunc() 
{ 
    struct sonicPins * pins; 
    pthread_create(&pt1, NULL, setup, (void*) pins); 
    pthread_create(&pt2, NULL, setup, (void*) pins); 
    pthread_create(&pt3, NULL, setup, (void*) pins); 
    pthread_create(&pt4, NULL, setup, (void*) pins); 
    return 1; 
} 

下面的代碼段的責任是設置引腳值和運行操作來管理傳感器。每個傳感器都有自己的回波和觸發值,它們是整數。

void* setup(void *pinsPtr) 
{ 
    struct sonicPins *ptr = pinsPtr; 
    int trig = 0, Echo = 0; 

    printf("thread id %d\n", pt1); 
    if (pt1 == 1993737328) { 
     trig = ptr->trig1; 
     Echo = ptr->echo1; 
    } else if (pt2 == 1986323568) { 
     trig = ptr->trig2; 
     Echo = ptr->trig2; 
    } else if (pt3 == 1977164912) { 
     trig = ptr->trig3; 
     Echo = ptr->trig3; 
    } else if (pt4 == 4) { 
     trig = ptr->trig4; 
     Echo = ptr->echo4; 
    } 
    …other work… 
} 

我是新來的C和沒有忘記一個線程ID並不總是相同的,但我不知道我可以使用的基礎上處理。你能提出一些建議嗎?

+4

爲什麼不創建自己的線程標識,例如'1,2,3,4',並將其傳入參數? –

+2

您每次調用'pthread_create()'時都會將相同的未初始化指針傳遞給該函數。這不會導致幸福。如果你不關心,你可以傳遞一個空指針,但是在實踐中,你應該傳遞一個單獨的數據結構,每次包含該函數需要操作的控制信息。功能沒有其他的方法來知道它應該做什麼。這就是函數的論點。並且不要在每次調用時重複使用相同的變量 - 調度不可預測。 –

+0

哪個指針爲空? –

回答

1

你需要的是一個結構數組,其中每個結構都有一個回顯和觸發值。然後,將不同的數組條目傳遞給每個線程,以便每個線程只知道它自己的回顯和觸發值。

#include <stdio.h> 
#include <pthread.h> 

typedef struct sonicPins { 
    int trig; 
    int echo; 
} sonicPins; 

void *threadFunc(void *args) 
{ 
    sonicPins *pins = args; 
    printf("trig=%d echo=%d\n", pins->trig, pins->echo); 
    return NULL; 
} 

int main(void) 
{ 
    pthread_t threadID[4]; 
    sonicPins pinsArray[4] = { { 1, 2 }, { 4, 8 }, { 16, 32 }, { 64, 128 } }; 

    for (int i = 0; i < 4; i++) 
    { 
     if (pthread_create(&threadID[i], NULL, threadFunc, &pinsArray[i]) != 0) 
      fprintf(stderr, "pthread_create failed: %d\n", i); 
    } 

    for (int i = 0; i < 4; i++) 
     pthread_join(threadID[i], NULL); 
} 
+0

好吧我明白不知道爲什麼我以前沒有考慮過使用二維數組。我認爲我的代碼應該運行的方式不會讓線程停下來,因爲傳感器需要始終保持活動狀態。 –

+0

嗯,是的,我想初始化器使它看起來像一個二維數組。 – user3386109

+0

是的,當我嘗試建議它說它不知道什麼sonicPins是你有sonicPins pinsArray [4]; sonicThread.c:7:5:error:'for'循環初始聲明只允許在C99模式下使用 sonicThread.c:7:5:注意:使用選項-std = c99或-std = gnu99來編譯代碼 sonicThread .c:8:5:錯誤:未知類型名稱'sonicPins' –