【发布时间】:2017-02-22 04:44:52
【问题描述】:
我要直截了当地说这是一项家庭作业。我非常接近,但有一件小事我无法弄清楚。该程序要求用户在一行中输入任意数量的数字。对于他们输入的每个数字,它都会创建一个新线程,然后打印出找到该数字的 Collatz 猜想的过程。
除了我无法使用 for 循环创建多个线程之外,我一切正常。我创建了一个线程数组,然后尝试为输入中的每个数字创建一个新线程,但似乎只创建一个线程然后退出程序。
关于它为什么不起作用的任何想法?
附: 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);
}
【问题讨论】: