2012-01-23 67 views
2

可能重複:
Multiple arguments to function called by pthread_create()?
How to pass more than one value as an argument to a thread in C?傳遞多個參數,以在pthread_create

我有這些結構:

struct Request { 
    char buf[MAXLENREQ]; 
    char inf[MAXLENREQ]; /* buffer per richiesta INF */ 
    int lenreq; 
    uint16_t port; /* porta server */ 
    struct in_addr serveraddr; /* ip server sockaddr_in */ 
    char path[MAXLENPATH]; 
    /*struct Range range;*/ 
}; 

struct RequestGet { 
    char buf[MAXLENREQ]; 
    int maxconnect; 
    struct Range range; 
}; 

struct ResponseGet{ 
    char buf[MAXLENDATA]; 
    //int LenRange; 
    int expire; 
    char dati[MAXLENDATA]; 
    struct Range range; 
}; 

我怎樣才能把它們傳遞給pthread_create ?不管每個結構領域的意義如何。

​​
+0

我已經看到了,但我的疑問是關於三種不同結構的malloc的... – rschirin

+0

的可能重複[多參數功能通過在pthread_create()調用?(http://stackoverflow.com /(問題/ 1352749 /),[pthreads和C++](http://stackoverflow.com/questions/2468113/),[將多個參數傳遞給C(pthread_create)中的一個線程](http://stackoverflow.com/questions/6524433 /) – outis

回答

6

您只能傳遞一個參數,因此您通常需要創建一個接受一個參數的函數,即使它只是包裝其他一些參數。您可以通過創建一個struct並使該函數獲取指向這樣一個struct的指針。

下面是一個基本的例子來說明這一點。請注意,它是不是一個完整的例子,並且應該不是原樣使用!請注意,例如,分配有malloc()的內存都不會被釋放。

struct RequestWrapper { 
    struct Request *request; 
    struct RequestGet *request_get; 
    struct ResponseGet *response_get; 
}; 

void thread_func(struct RequestWrapper *rw) { 
    // function body here 
} 

int main(int argc, char *argv[]) { 
    struct Request *request = malloc(sizeof(*request)); 
    struct RequestGet *request_get = malloc(sizeof(*request_get)); 
    struct ResponseGet *response_get = malloc(sizeof(*response_get)); 
    ... 

    struct RequestWrapper *wrapper = malloc(sizeof(*wrapper)); 

    wrapper->request = request; 
    wrapper->request_get = request_get; 
    wrapper->response_get = response_get; 

    ... 

    pthread_create(&id, NULL, thread_func, &wrapper); 
    ... 
} 
+0

危險不完整。看到我的評論來爆裂。 –

+0

@R ..這個想法是讓他開始了他不明白的概念,而不是寫一大堆其他的代碼。毫無疑問,最好的例子是那些按原樣運行的例子,但是這個想法讓我們知道如何傳遞多種東西,我認爲它恰當地傳達了這一點。然而,我會添加一個註釋,指出它的不完整性。 –

+0

那麼問題是,你「讓他開始」的代碼可能會工作99%的時間和崩潰或其他1%的時間可怕地損壞內存。初學者不太可能意識到這一點,更不知道如何回去修復它。 –

0

pthread_create()最後一個參數是一個空指針。它的名稱是,你可以讓它指向任何類型的變量,結構等。你的thread_func知道如何處理它,並可以將其轉換回原來的類型。

0

將他們的地址放入struct,並將指針傳遞給struct作爲pthread_create()的最後一個參數。

2
struct Foo { 
    // anything you want 
}; 

void run (void * _arg) { 
    Foo * arg = (Foo*) _arg; 
    // ... 
} 

int main() { 
    pthread_t thread; 
    Foo * foo = create_argument(); 

    pthread_create (&thread, NULL, run, foo); 
} 

這取決於,當然,前提是run將一直被賦予在最後一個參數一個Foo*pthread_create的合同。

+1

此答案危險地不完整;正如所寫的,'foo'的生命週期可能在'run'能夠使用它之前結束。你必須爲'foo'分配'malloo'的空間(並且在新線程中釋放'free',而不是父線程!),或者使用一些同步對象(barrier或信號量最簡單)來確保'foo''他的一生不會很快結束。 –

+0

好點,編輯。 – spraff

0

您可以爲所有數據創建一個結構並傳遞該結構的地址。您可能需要將結構放入堆中並在完成時釋放它。