我幾乎完成了我在哪裏需要使用並行線程的家庭作業。我已經想出了pthreads。我留下的唯一問題是弄清楚如何通過pthread_create()將多個參數傳遞給線程。「非鑄造」從(無效*)和間接引用到字符數組
我需要兩個字符傳遞給線程。我必須將它們轉換爲(* void)以與pthread_create()一起使用。我可以通過它們,但我不知道如何從函數中的*參數中獲取值。
void *my_function(void *parameter) {
/* ATTEMPT 1 - DOESN'T WORK */
//char* arguments[2];
//arguments = (char * [2]) parameter;
/*Error message:
error: ISO C++ forbids casting to an array type char* [2] [-fpermissive]
error: incompatible types in assignment of char** to char*[2]
*/
/* ATTEMPT 2 - DOESN'T WORK */
//char *my_data = (char *)parameter;
//my_data is blank when I try to use cout to check it's values
/* What I need to do is get those two chars from the array and print them out as part of this thread function */
pthread_exit(NULL);
}
int main(int argc, char **argv) {
char duration = '5'; //in reality, this value is taken from argv but I am leaving that out for brevity
pthread_t threads[3];
for(int i=0; i < 3; i++){
char thread_args[2] = {i, duration};
//create thread with arguments passed in
int results = pthread_create(&threads[i], NULL, my_function, (void *) &thread_args);
//testing for pthread error
if (results){
printf("ERROR; return code from pthread_create() is %d\n", results);
exit(-1);
}
}
/* Wait for all threads to complete */
for (int j=0; j < num_threads; j++) { // https://computing.llnl.gov/tutorials/pthreads/
pthread_join(threads[j], NULL);
}
/* some information prints here that is unrelated to my problem (the date, time, etc) */
pthread_exit(NULL);
}
我能夠通過一個值沒有問題。有什麼建議麼?
最接近的現存的問題,我能找到的就是這一點,但我還是感到有沒有運氣:Converting from void* to char ** in C
謝謝!
創建一個陣列或結構與兩個字符和一個指針傳遞給任何一個。 – 2013-03-12 00:11:36
@ Code-Guru:'thread_args'似乎已經是一個包含兩個字符的數組。 – aschepler 2013-03-12 00:13:59
@kelseyelayne:你知道''1'和'1'之間的區別嗎? – aschepler 2013-03-12 00:15:52