我写了四个不同的程序来计算两个文件中的总字数.这四个版本看起来大致相同.前三个版本使用两个线程进行计数,只有三个语句的顺序不同.最后一个版本使用一个线程来计算.我将首先列出每个版本的不同部分和公共部分,然后列出每个版本的输出和我的问题.
不同部分:
// version 1
count_words(&file1);
pthread_create(&new_thread, NULL, count_words, &file2);
pthread_join(new_thread, NULL);
// version 2
pthread_create(&new_thread, NULL, count_words, &file2);
count_words(&file1);
pthread_join(new_thread, NULL);
// version 3
pthread_create(&new_thread, NULL, count_words, &file2);
pthread_join(new_thread, NULL);
count_words(&file1);
// version 4
count_words(&file1);
count_words(&file2);
Run Code Online (Sandbox Code Playgroud)
常见部分:( 将不同部分插入此公共部分以制作完整版本)
#include <stdio.h>
#include <pthread.h>
#include <ctype.h>
#include <stdlib.h>
#include <time.h>
#define N 2000
typedef struct file_t {
char *name;
int words;
} file_t;
double time_diff(struct timespec *, struct timespec *);
void *count_words(void *);
// Usage: progname file1 file2
int main(int …Run Code Online (Sandbox Code Playgroud)