pthread を使用する必要がある宿題をほぼ完了しました。私はpthreadsを理解しました。私が残した唯一の問題は、pthread_create() を介してスレッドに複数の引数を渡す方法を理解することです。
スレッドに 2 文字を渡す必要があります。pthread_create() で使用するには、それらを (*void) にキャストする必要があります。それらを渡すことはできますが、関数の *parameter から値を取得する方法がわかりません。
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);
}
問題なく 1 つの値を渡すことができました。助言がありますか?
私が見つけた最も近い既存の質問はこれでしたが、まだ運がありません: Converting from void* to char ** in C
ありがとうございました!