我将直挺挺地说,这是一项家庭作业。我非常接近,但有一件事我不明白。该程序要求用户在一行中输入任意数量的数字。对于他们输入的每个数字,它将创建一个新线程,然后打印出找到该数字的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