2017-02-22 43 views
0

我將直挺挺地說,這是一項家庭作業。我非常接近,但有一件事我不明白。該程序要求用戶在一行中輸入任意數量的數字。對於他們輸入的每個數字,它將創建一個新線程,然後打印出找到該數字的Collat​​z猜想的過程。通過一系列線程循環

我有一切工作,但事實上我不能使用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); 
} 

回答

1

您不應該在void *updater(int num)中撥打pthread_exit(0),因爲它會終止您的程序。您只需從此方法返回NULL

等到您創建所有線程後再加入它們。加入一個線程將等待它完成,因此一旦創建線程就加入線程並不會帶來任何好處。這應該看起來像這樣:

for (j = 0; j < size; j++) { 
    pthread_create(&tid_array[j], &attr, updater(nums[j]), NULL); 
} 

for (j = 0; j < size; j++) { 
    pthread_join(&tid_array[j], NULL); 
} 
+0

這可以工作,但現在一旦它打印出來並打印出每個數字,它就沒有達到用戶可以選擇輸入更多數字或退出的點。它打印出第二個提示,但之後退出。 – MrWhiteNerdy

1
 for (j = 0; j < size; j++) { 
      pthread_create(&tid_array[j], &attr, updater(nums[j]), NULL); 
      pthread_join(&tid_array[j], NULL); 
     } 

加入一個線程等待它完成,所以你只能同時運行一個線程。相反,首先創建所有線程。然後,當你想等待他們全部完成時加入他們(或者如果你不這樣,他們會分開他們)。