Help with multithreads in C
Here is my current code. I also have text file with the following sentence 3 times, It is a "test" file, and it is very large. And it can have one single line or multiple lines.
When i run and compile my code, It will ask me to input a number of threads. When i enter a number, the it outputs the following: len = 107, size = 27, segmentation fault = 11.
However when, running the code this is what should be outputted: a3 and 6 can 3 file 3 have 3 is 6 it 9 large 3
Thanks for any help, it will be greatly appreciated.
#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);
int i,c;
i=0;c=0;
enum states { WHITESPACE, WORD };
int state = WHITESPACE;
fseek(td->fp, td->offset, td->start);
char last = ' ';
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 )
{
words++;
}
state = WORD;
}
last = buffer[0];
}
free(buffer);
pthread_exit(NULL);
return NULL;
}
int main(int argc, char **argv)
{
int nthreads, x, id, blockSize,len;
FILE *fp;
pthread_t *threads;
struct thread_data data[nthreads];
if (argc < 2)
{
fprintf(stderr, "Usage: ./a.out <file_path>");
exit(-1);
}
if((fp=fopen(argv[1],"r"))==NULL)
{
printf("Error opening file");
exit(-1);
}
printf("Enter the number of threads: ");
scanf("%d",&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);
//free(threads);
//pthread_exit(NULL);
printf("%d\n",words);
return 0;
}
Posted Dec 2, 2015, 10:57 PM UTC · edited
012