首页 > 解决方案 > 在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;  
} 

标签: c

解决方案


推荐阅读