2013-05-08 47 views
1

所以我有這個憋屈線程問題

void* tf(void* p); 

我不完全理解。我認爲它是一個帶有void參數指針的函數指針。我用它來讓一個線程是這樣的:

pthread_create(&thread_id[i], NULL, tf, NULL); 

我需要的是TF和如何的expliation一個參數傳遞給它。

我具備的功能定義爲

void* tf(void* p) 
{ 
    //I would like to use p here but dont know how. 
} 

此功能外主,需要得到被設置裏面主要其他一些參數。我試圖讓它看起來像這個tf(int i),但我然後得到一個段錯誤。所以我知道我做錯了什麼,需要一些幫助來搞清楚。

感謝您在這方面的任何幫助。

傑森

+0

http://linux.die.net/man/3/pthread_create – 2013-05-08 13:50:45

回答

1
pthread_create(&thread_id[i], NULL, tf, NULL); 
//          ^^^^^ 
//      You have to put here the pointer (address) to your data 

,然後你可以從p指針您的數據到線程函數

typedef struct test { 
    int a,b; 
} test; 

int main() 
{ 
    struct test T = {0}; 
    pthread_create(&thread_id[i], NULL, tf, &T); 
    pthread_join(thread_id[i], NULL); // waiting the thread finish 
    printf("%d %d\n",T.a, T.b); 
} 

void* tf(void* p) 
{ 
    struct test *t = (struct test *) p; 
    t->a = 5; 
    t->b = 4; 
} 
0

pthread_create最後一個參數傳遞給線程函數。

所以在你的情況下,定義你想要傳遞給線程函數的東西,就像在線程創建函數中傳遞它的地址一樣。像

//in main 
char *s = strdup("Some string"); 
pthread_create(&thread_id[i], NULL, tf, s); 
... 

void* tf(void* p) 
{ 
    char *s = (char *) p; 
    // now you can access s here. 

} 
0

回調函數的void參數可以是指向任何你想要它的指針或什麼都沒有(NULL)。你只需要正確地施放它。函數tf本身就是預期執行子線程工作的函數,並且如果您希望它在退出時返回某種值,則將其作爲指針返回,就像您在傳遞參數時所做的那樣線程。

struct settings 
{ 
    int i; 
    int j; 
    char* str; 
}; 

void* tf(void* args) 
{ 
    int result = 0; 

    struct settings* st = (struct settings*)args; 

    // do the thread work... 

    return &result; 
} 

int main(int argc, char** argv) 
{ 
    struct settings st; 

    st.i = atoi(argv[1]); 
    st.j = atoi(argv[2]); 
    st.str = argv[3]; 

    pthread_create(&thread_id[i], NULL, tf, &st); 

    // do main work... 
} 
0

tf僅僅是接收void *參數,並在端部返回void *值的函數。目前沒有函數指針。

pthread_create需要一個指向函數的指針才能執行,所以你不需要通過tf,而是通過&tf來傳遞tf的位置。

void *在C中只是一個完全通用的指針。所以,你將它轉換爲無論你是在傳遞,從而:

int a = 4; 
void * a_genptr = (void *)&a; 
pthread_create(... &tf ... a_genptr ...); 

void * tf(void * arg) { 
    int thatIntIWanted = *(int *)arg; // cast void * to int *, and dereference 
} 

你可以看到this other SO question

+0

感謝這樣一個例子解釋。這些一定會幫助我解決問題。當我有一些時間時,我會試試這個。 – Xintaris 2013-05-09 20:50:04