Wrong Output using Mutex and Pthread Library

The purpose of the below program is to learn Mutex and Pthread library. The main() creates three thread. (thread 1, 2 & 3).
Each thread one-by-one sequentially, reads one character per file (different file) and stores into the global constant.
Example thread 1 reads character ‘a’ from file1, then wait for thread 2 & 3 to the same (i.e. read ‘b’ and ‘c’ from file2 and file3 respective).

Once the reading is finished, we want the main to print the global constant to file.out

I have attempted to program the same but getting incorrect output.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdbool.h>

char glob_var, strtemp[1024];
pthread_mutex_t lock;
int cnt = 0;
char inp[3][10] = {"file-1.in", "file-2.in", "file-3.in"};

void * thread_func(void * arg);

void * thread_func(void * arg)
{
    FILE *fp;
    char * argu = (char *)arg;
    fp = fopen(argu, "r");
    while (1) {
        pthread_mutex_lock(&lock);
        glob_var = fgetc(fp);
        if(feof(fp))
        { 
            pthread_mutex_unlock(&lock);
            break ;
        }
        if (glob_var != 'n')
            strtemp[cnt++] = glob_var;
        pthread_mutex_unlock(&lock);
    }
    fclose(fp);

    return (void *)0;
}

int main(void)
{
    FILE * fpout;
    pthread_t threads[3];
    int i = 0;

    fpout = fopen("file.out", "w");

    for (i = 0; i < 3; i++)
        pthread_create(&threads[i], NULL, thread_func, (void *)inp[i]);

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

    strtemp[cnt] = '{$content}';
    cnt = 0;

    while(1) {
        glob_var = strtemp[cnt++];
        fprintf(fpout, "%cn", glob_var);
        if (strtemp[cnt] == '{$content}') {
            break;
        }
    }
    fclose(fpout);

    return 0;
}

Input File

File1 File2 File3
a     u     t
o     .     #
e     p     a
i     r     m
e     n     $

Output File

From Above Code         Desired Output
t                       a
#                       u
r                       t
a                       o
m                       .
!                       #
$                       e
s                       p
m                       a
u                       i
.                       r
p                       m
r                       e
n                       n


Source: c#

Leave a Reply