我有下面的代碼,但我不明白為什么結果沒有正確列印出來。我將 val 分配為我想要獲得的結果數量的大小。我在 val 中傳遞了我想要保存結果的位置的地址。
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>
void* roll_dice() {
int value = (rand() % 6) 1;
int* result = malloc(sizeof(int));
*result = value;
// printf("%d\n", value);
printf("Thread result: %p\n", result);
return (void*) result;
}
int main(int argc, char* argv[]) {
int NUM_DICE = 4;
srand(time(NULL));
pthread_t th[NUM_DICE];
for (int i = 0; i < NUM_DICE; i ) {
if (pthread_create(&(th[i]), NULL, &roll_dice, NULL) == -1) {
perror("failure");
}
}
int* val = calloc(NUM_DICE, sizeof(int));
for (int i = 0; i < NUM_DICE; i ) {
pthread_join(th[i], &val); // this doesn't work
// pthread_join(th[i], &(val i)); // this doesn't work
printf("%d\n", *val);
}
for (int i = 0; i < NUM_DICE; i ) {
printf("Dice %d rolled %d\n", i 1, *(val i));
}
return 0;
}
uj5u.com熱心網友回復:
malloc如果成功則回傳void*,您需要將其轉換為int*.的第三個引數
pthread_createisvoid(*)(void*), notvoid(*)(),所以roll_dice()需要一個void*引數。我們可以使用一個陣列來存盤執行緒的回傳值。
畢竟,我們需要釋放我們使用 malloc 分配的記憶體。
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>
void* roll_dice(void*) {
int value = (rand() % 6) 1;
int* result = (int*)malloc(sizeof(int));
*result = value;
// printf("%d\n", value);
printf("Thread result: %p\n", result);
return (void*) result;
}
int main(int argc, char* argv[]) {
int NUM_DICE = 4;
srand(time(NULL));
pthread_t th[NUM_DICE];
for (int i = 0; i < NUM_DICE; i ) {
if (pthread_create(&(th[i]), NULL, &roll_dice, NULL) == -1) {
perror("failure");
}
}
int* val[NUM_DICE];
for (int i = 0; i < NUM_DICE; i ) {
pthread_join(th[i], (void**)&val[i]); // this doesn't work
// pthread_join(th[i], &(val i)); // this doesn't work
printf("%d\n", *val[i]);
}
for (int i = 0; i < NUM_DICE; i ) {
printf("Dice %d rolled %d\n", i 1, *(val[i]));
}
for (int i = 0; i < NUM_DICE; i ) {
free(val[i]);
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/424580.html
下一篇:Python中信號量的使用
