I have one thread that locks a mutex, writes a value to a variable, unlocks the mutex. I do a print out here and the value has been changed. I set it to 1.
When I read the variables value in another thread using lock, unlock on the mutex and read the value, I get the old value of 0.
Why is this happening. I lock and unlock the same mutex correctly.
How do I sync threads?
EDIT:
I declare the mutexes and variables here
static pthread_mutex_t movementIdMutex = PTHREAD_MUTEX_INITIALIZER;
static int nav_movementId = 0;
static pthread_mutex_t newMovementMutex = PTHREAD_MUTEX_INITIALIZER;
static int nav_newMovement = 0;
I set the variables here
void nav_setMovementIdentifier(int id)
{
printf("Received movement id:%d from connectivity\n", id);
int result; /* Use the result for testing */
result = pthread_mutex_lock(&movementIdMutex);
nav_movementId = id;
printf("nav_movementId is %d\n", nav_movementId);
result = pthread_mutex_unlock(&movementIdMutex);
result = pthread_mutex_lock(&newMovementMutex);
nav_newMovement = 1;
printf("nav_newMovement is %d in the setId function\n", nav_newMovement);
result = pthread_mutex_unlock(&newMovementMutex);
printf("\n");
}
and read them here
void *startConnectivityListener(void *ptr) {
/* Declare safety variables because segments cant be locked/unlocked
* using mutexes if they are checking in statement such as if and while.
*/
int newMoveCheck = 0;
int startIndoorCheck = 0;
int startOutdoorCheck = 0;
int listening = 1;
while(listening == 1)
{
int result; /* Use for testing */
/* check if a new movement command waits */
result = pthread_mutex_lock(&newMovementMutex);
newMoveCheck = nav_newMovement;
printf("nav new movement in thread is :%d\n", nav_newMovement);
printf("newMoveCheck in mutex lock is:%d\n", newMoveCheck);
result = pthread_mutex_unlock(&newMovementMutex);
result = pthread_mutex_lock(&movementIdMutex);
printf("nav_movementId in thread is %d\n", nav_movementId);
result = pthread_mutex_unlock(&movementIdMutex);
printf("newMoveCheck is %d\n", newMoveCheck);
sleep(1);
if(newMoveCheck == 1)
I get the correct print outs in the setter functions printf statements, it set the values to id that is passed in and to 1.
When I try print it where I read them, both are still showing 0, which is what they were set to when I initialized them.