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