나는 조금 더 나아가 this exercise을 따라 갔으며 업데이트 된 코드로 답변을 게시하거나 원래 게시물을 편집하거나 새로운 질문을해야하는지 확실하지 않았습니다. 프로토콜을 따르지 않을 경우 조언하십시오.멀티 스레드 : 스레드를 시작하고 종료 할 때
지금까지 입력 파일에서 읽은 모든 정수를 배열에 할당했습니다. 그런 다음 전체 정수 수 (색인)를 스레드 수 (number_of_threads)로 나눠서 최적의 numbers_per_thread을 찾았습니다.
그런 다음 배열의 모든 숫자를 증가시키면서 각 블록을 최적의 numbers_per_thread에 따라 할당하는 while 루프를 만듭니다.
prob_5.c
#include <stdio.h>
int main(int argc, char *argv[]) {
int i, j;
FILE *fp;
int values[15000];
char line[32];
int index = 0;
int number_of_threads = 10;
int numbers_per_thread;
for (i = 1; i < argc; i++) {
fp = fopen(argv[i], "r");
if (fp == NULL) {
fprintf(stderr, "cat: can't open %s\n", argv[i]);
continue;
}
while (fgets(line, sizeof(line), fp) != NULL && (index < 15000)) {
sscanf(line, "%d", &values[index]);
index++;
}
fclose(fp);
}
numbers_per_thread = index/number_of_threads;
while (i < index) {
for (j = 0; (j < numbers_per_thread) && (i < index); j++) {
i++;
j++;
}
}
printf("%d\n", index);
return 0;
}
내가 스레드의 시작 및 중지를 처리하는 방법에 관한 혼란 스러워요. for (j = 0; ..) 루프 내에서 시작하고 스레드를 종료하기 위해 if (j == numbers_per_thread)를 작성해야합니까? 각 스레드에 대한 숫자 블록을 저장할 새 배열을 작성해야합니까? 나는 pthread_create, pthread_join 등을 사용하는 방법에 대해 혼란스러워한다. 처음 사용하는 것이기 때문에.
제안 해 주셔서 감사합니다. 나는 pthread_t threads [number_of_threads]를 추가했고 for 루프를 만들었습니다 : for (i = 0; i
raphnguyen