|
making fuction thread safe
Hi all,
I'm trying to understand the idea of making a function only readable by one thread at once. I've got a function to read a commsport, I've set up a mutext the way I thought it should be, however my function is only read once, and then lock out. Can anyone advise?
I've set up the thread with
pthread_mutex_t rxmutex = PTHREAD_MUTEX_INITIALIZER
my fuction is
char RxChar(COMPORT *port)
{
char readletter[3];
pthread_mutex_lock( &rxmutex ); /*lock thread*/
if(read(port->id, readletter, 1)==-1) /* comms port has nothing*/
{
pthread_mutex_unlock( &txmutex); /*unlock*/
return(-1);
}
else
{
pthread_mutex_unlock( &rxmutex); /*unlock*/
return(readletter[0],readletter[0]);
}
pthread_mutex_unlock( &txmutex); /*just to be safe*/
return(-1);
}
my code work as if I remove the mutex stuff it's Ok. My understanding of threads self taught as I normally work on embedded stuff with interupts so I hope someone can explain this. It needs to be thread safe as the diffrent ports are called from diffrent threads. Thanks in advance.
|