shre3841279
shre3841279

Reputation: 33

File operations using POSIX threads

I am learning the concept of multithreading and i encountered a problem using semaphore mutexes.

Here is my code snippet:

void *thread1_funct(void * myfileptr)
{
static int count;
printf("\nThread1 ID:%u\n",(unsigned int) pthread_self());
printf("\nThread1 function, file pointer received:0x%x\n", (FILE*)myfileptr);

for (;;)
{
count++;
sem_wait(&mutex);
fprintf(myfileptr, "%d\n", count);
sem_post(&mutex);
}

return NULL;
}


void *thread2_funct(void *myfileptr)
{
static int count=0;

printf("\nThread2 ID:%u\n",(unsigned int) pthread_self());
printf("\nThread2 function, file pointer received:0x%x\n", (FILE*)myfileptr);

for (;;)
{sem_wait(&mutex);
fscanf(myfileptr, "%d\n", &count);
printf("\n......%d......\n", count);
sem_post(&mutex);
}

return NULL;
}

The two threads i have created. One will write dfata to a file and the other will read the latest data.

Here is my main method:

int main(int argc, char **argv)
{
FILE *fileptr = fopen(*(argv+1), "a+");

sem_init(&mutex, 0x00, 0x01);

if ( (thread1_ret = pthread_create(&thread1, NULL, thread1_funct, (void*)fileptr)) == 0)
printf("\nThread1 created successfully....\n");
else
printf("\nFailed to create Thread1\n");

if ( (thread2_ret = pthread_create(&thread2, NULL, thread2_funct, (void*)fileptr)) == 0)
printf("\nThread2 created successfully....\n");
else
printf("\nFailed to create Thread2\n");

pthread_join(thread1, NULL);                                 
pthread_join(thread2, NULL);                                 

fclose(fileptr);

sem_destroy(&mutex);

pthread_exit(NULL);
return 0;
}

The expected output is : ........1........ ........2........ ........3........

and so on...... till the program is interrupted manually.

But my output is all 0s: ........0....... ........0....... ........0....... ........0.......

and so on....

Please help me. Where am i going wrong?

Upvotes: 0

Views: 566

Answers (1)

Greycon
Greycon

Reputation: 789

Thread 1 writes to the file, and advances the file pointer - to the end of the file. Thread 2 reads from the file pointer, which is pointing at the end of the file, and so you get nothing.

You could use fseek, or rewind in thread 2 to get your data.

Upvotes: 1

Related Questions