利用Linux编写代码实现上面的实验
时间: 2024-02-12 17:15:26 浏览: 22
以下是一个简单的 C 语言程序,实现了上述实验:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <pthread.h>
#define THREAD_NUM 4 // 线程数
#define MAX_FILENAME 1024 // 文件名最大长度
#define MAX_LINE_LEN 1024 // 每行最大长度
int word_count = 0; // 单词计数器
pthread_mutex_t mutex; // 互斥锁
void *count_words(void *arg);
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("Usage: %s <filename>\n", argv[0]);
return 1;
}
char filename[MAX_FILENAME];
strncpy(filename, argv[1], MAX_FILENAME);
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("Failed to open file %s\n", filename);
return 1;
}
char line[MAX_LINE_LEN];
char *content = NULL;
size_t content_len = 0;
while (fgets(line, MAX_LINE_LEN, fp) != NULL) {
size_t len = strlen(line);
content = realloc(content, content_len + len + 1);
if (content == NULL) {
printf("Memory allocation error\n");
return 1;
}
strncpy(content + content_len, line, len);
content_len += len;
}
fclose(fp);
pthread_t threads[THREAD_NUM];
pthread_mutex_init(&mutex, NULL);
for (int i = 0; i < THREAD_NUM; i++) {
pthread_create(&threads[i], NULL, count_words, (void *) content);
}
for (int i = 0; i < THREAD_NUM; i++) {
pthread_join(threads[i], NULL);
}
printf("Word count: %d\n", word_count);
pthread_mutex_destroy(&mutex);
free(content);
return 0;
}
void *count_words(void *arg)
{
char *content = (char *) arg;
int start = (int) ((long) content) % THREAD_NUM;
int end = strlen(content);
for (int i = start; i < end; i += THREAD_NUM) {
if (isalnum(content[i])) {
continue;
}
if (i > 0 && isalnum(content[i - 1])) {
pthread_mutex_lock(&mutex);
word_count++;
pthread_mutex_unlock(&mutex);
}
}
pthread_exit(NULL);
}
```
该程序将读取指定文件中的所有内容,并将其存储在一个字符串中。然后,创建了一定数量的线程,每个线程负责处理字符串的一部分。在处理字符串时,当遇到一个单词时,就将计数器变量加一。在多个线程同时修改计数器变量时,使用互斥锁来保护它,确保线程间的同步和协作。最后,输出计数器变量的值,即单词数。