c - 在Linux上使用C创建一个多线程pthread程序,计算文本fi中的单词数
问题描述
我对 linux 和 C 很陌生。对于我的操作系统类,我们应该编写一个代码,将文本文件划分为 8 个段。程序不能手动分区。我在命令行中使用了 gcc assign4.c -Wall -Werror -pthread 并且它处理代码没有错误。然后我输入./a.out,打印出来的是“Assign4.txt”。有人可以指导可能出了什么问题吗?
下面是代码:
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
struct thread_data
{
FILE *fp;
long int offset;
int start;
int blocksize;
};
int words = 0;
void *countFrequency(void* data)
{
struct thread_data* td=data;
char *buffer = malloc(td->blocksize);
enum states {WHITESPACE, WORD};
int state = WHITESPACE;
fseek(td->fp,td->offset,td->start);
while ((fread(buffer,td->blocksize,1,td->fp))==1)
{
if (buffer[0]==' '||buffer[0]=='\t')
{
state = WHITESPACE;
}
else if (buffer[0]=='\n')
{
state = WHITESPACE;
}
else
{
if (state == WHITESPACE)
{
state = WORD;
words++;
}
}
free(buffer);
pthread_exit(NULL);
}
return NULL;
}
int main(int argc,char **argv)
{
int nthreads, id, blockSize,len;
FILE *fp;
pthread_t *threads;
if (argc < 2)
{
fprintf(stderr, "Assign4.txt");
exit(-1);
}
if ((fp=fopen(argv[1],"r"))== NULL)
{
printf("Error opening file");
exit(-1);
}
printf("Enter filename: ");
scanf("%d",&nthreads);
struct thread_data data[nthreads];
threads = malloc(nthreads*sizeof(pthread_t));
fseek(fp, 0, SEEK_END);
len = ftell(fp);
printf("len= %d\n",len);
blockSize = (len+nthreads-1)/nthreads;
printf("size= %d\n",blockSize);
for(id = 0; id < nthreads; id++)
{
data[id].fp=fp;
data[id].offset = blockSize;
data[id].start = id*blockSize+1;
}
data[nthreads-1].start = (nthreads-1)*blockSize+1;
for(id = 0; id < nthreads; id++)
pthread_create(&threads[id], NULL,
&countFrequency,&data[id]);
for(id = 0; id < nthreads; id++)
pthread_join(threads[id],NULL);
fclose(fp);
printf("Total: %d\n", words+1);
return 0;
}
解决方案
推荐阅读
- dialogflow-es - 无法访问要发布的代理设置
- python - 在没有 for 循环的情况下对数组元素进行操作
- python - 使用 Python 作为具有有限权限的客户端连接到 Firestore
- javascript - 赛普拉斯主机名插件没有响应
- java - 有什么方法可以将这个 onMouseEntered 应用于 FXML 文件中的所有按钮,而无需为每个按钮实际编写单独的代码?
- python - python requests .encode("utf-8") 导致内部服务器错误
- spring-boot - 具有未知数据源的 Spring Batch
- javascript - 在sequelize中使用where条件根据距离进行过滤
- c - 为什么将指针作为函数参数传递时出现分段错误?
- python - Python Tkinter 多项选择测验 - 更改按钮颜色以显示正确答案