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?
mutexfor a semaphore is likely to be confusing down the road - and in this case you should probably be using amutexanyway, not a semaphore (not because the semaphore won't work, though - it's just a bigger hammer than you need for that job). In addition @Greycon's answer below about the file pointer position, it's quite possible due to buffering that the data never gets written out anyway - at least for some time...flush()after each write or use unbuffer I/O, that isopen(),write(),read()andclose()and two file descriptors.