我將直挺挺地說,這是一項家庭作業。我非常接近,但有一件事我不明白。該程序要求用戶在一行中輸入任意數量的數字。對於他們輸入的每個數字,它將創建一個新線程,然後打印出找到該數字的Collatz猜想的過程。通過一系列線程循環
我有一切工作,但事實上我不能使用for循環創建多個線程。我創建了一個線程數組,然後嘗試爲輸入中的每個數字創建一個新的線程,但似乎只創建一個線程,然後退出該程序。
爲什麼它不工作的任何想法?
P.S. C絕對不是我的強項,這只是我寫的第三個程序。所以我仍然在學習和努力與語言。
代碼:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
void *updater(int num);
int main() {
pid_t pid;
char input[50];
int nums[100], size = 0, j;
char *pch;
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed");
} else if (pid == 0) {
printf("Enter any number(s) or 'q' to quit: ");
fgets(input, sizeof(input), stdin);
while (strcmp(input, "q") != 1) {
pch = strtok(input, " ");
while (pch != NULL) {
nums[size] = atoi(pch);
size++;
pch = strtok(NULL, " ");
}
pthread_t tid_array[size];
pthread_attr_t attr;
pthread_attr_init(&attr);
for (j = 0; j < size; j++) {
pthread_create(&tid_array[j], &attr, updater(nums[j]), NULL);
pthread_join(&tid_array[j], NULL);
}
size = 0;
printf("Enter any number(s) or 'q' to quit: ");
fgets(input, sizeof(input), stdin);
}
} else {
wait(NULL);
}
return 0;
}
void *updater(int num) {
printf("%d ", num);
while (num != 1) {
if (num <= 0) {
printf("You cannot enter a negative number or 0\n");
return;
} else if (num % 2 == 0) {
num = num/2;
} else {
num = 3 * num + 1;
}
printf("%d ", num);
}
printf("\n");
pthread_exit(0);
}
這可以工作,但現在一旦它打印出來並打印出每個數字,它就沒有達到用戶可以選擇輸入更多數字或退出的點。它打印出第二個提示,但之後退出。 – MrWhiteNerdy