Souradeep Basu Souradeep Basu - 2 months ago 17
C Question

Multiple file access using threads

I am using multiple threads to access various random files using threads. However, I get an error

[Thread 0x7ffff7007700 (LWP 16256) exited]
. Also, info threads shows that only 2 threads are created. However, I am trying to create 100 of them. Also, do I have to use the pthread_join() function in my case? The code:

#define NTHREADS 100
void *encrypt(void *args)
{
int count = *((int*) args);
AES_KEY enc_key;
AES_set_encrypt_key(key, 128, &enc_key);

int i;

for(i=1;i<=count;i++){

char *ifile;
char *ofile;
long length;
size_t result;
char * buffer;

sprintf(ifile,"random_files/random_%d.txt",i);
FILE *ifp = fopen(ifile,"rb");

if (ifp==NULL) {fputs ("File error",stderr); exit (1);}

fseek(ifp,0, SEEK_END);
length = ftell(ifp);
fseek (ifp,0, SEEK_SET);

buffer = (char*) malloc (sizeof(char)*length);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
result = fread (buffer, 1, length, ifp);
if (result != length) {fputs ("Reading error",stderr); exit (3);}
printf("%s",buffer);
fclose (ifp);
free(buffer);
}
}
int main(){
int i,j,count =0;
pthread_t threads[NTHREADS];

for (i=0; i<NTHREADS; i++){
count = count +20;
int *count_ptr = &count;
if(pthread_create(&threads[i], NULL, encrypt, count_ptr)!=0){
fprintf(stderr, "error: Cannot create thread # %d\n", i);
break;
}
}

printf("After Thread\n");
exit(0);
}

Answer

Yes, you should join your threads, as none were created detached (and you're probably not deep enough in learning pthreads to deal with that anyway).

That said, you have a significant logic problem in your thread parameters. They're all getting the address of the same count variable in main. Probably the fastest way to change that with no modifications to your thread-proc is simply stand up a side-by-side array of int counts[NTHREADS] matching your threads, using each element as the corresponding thread's data param:

int main()
{
    pthread_t threads[NTHREADS];
    int counts[NTHREADS]; // HERE
    int i,j,count =0;

    for (i=0; i<NTHREADS; i++)
    {
        counts[i] = (count += 20);
        if(pthread_create(&threads[i], NULL, encrypt, counts+i)!=0) // LAST PARAM
        {
            fprintf(stderr, "error: Cannot create thread # %d\n", i);
            break;
        }
    }

    for (i=0; i<NTHREADS; ++i)
        pthread_join(threads[i], NULL));

    return EXIT_SUCCESS;
}

Alternatively, you could do some dynamic allocation hoops, or send the value via intptr_t, cast to void*, but the method shown above has the advantage of requiring no changes on your thread-proc, a target I was aiming for.

I've left any issues in your thread proc to you to solve, but that should get you up and running on your thread stack, at least.