0

I've got a simple program that echoes out the character that was entered by the user. Two threads are created to run this echo function and I'm using pthread mutex to lock the critical code to one process at a time so that the character is properly printed out:

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

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

char characterIn, characterOut;

void* echoCharacter()
{
    pthread_mutex_lock(&mutex);
    /* crital code start */
    characterIn = getchar();
    characterOut = characterIn;
    putchar(characterOut);
    /* crital code end */
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}

int main()
{
    //spawn
    pthread_t id;
    pthread_t id1;
    pthread_create(&id, NULL, echoCharacter, NULL);
    pthread_create(&id1, NULL, echoCharacter, NULL);
    //wait 
    pthread_join(id, NULL);
    pthread_join(id1, NULL);

    return 0;
}

However I'm not getting the correct output. It only echoes out the first character entered by the first thread, but the program stops after that and doesn't ask to enter another character:

>>a
>>a
>>

expected output:

>>a
>>a
>>b
>>b
Kaskader
  • 35
  • 1
  • 5

1 Answers1

2

If you're entering a on a line (followed by the ENTER key), that actually is two characters, the a and the \n.

If you enter ab with no intervening ENTER, you should see ab echoed back (once you hit ENTER afterwards, since your console is most likely in cooked mode).

A quick confirmation can be had by simply placing an extra getchar() to "swallow" the newline:

characterIn = getchar();
getchar();
characterOut = characterIn;

This is for debugging purposes, it's not really a viable solution. A viable solution would be to use line-based input, such as detailed here.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Oh wow I totally forgot about that. I thought it was an entirely different issue. Feel dumb now that it was that simple – Kaskader Sep 24 '18 at 02:28