Multithreaded code bug

Anyone would know why the following code not running as expected. It is quite intermittent; sometimes you would get the message print and other times you won't. Not sure what i am missing but the code looks legit and i am not sure what may cause the message "re-setting timer value . . .\n" to be printed so randomly. Thanks.

#include <iostream>
#include <pthread.h>

using namespace std;

pthread_mutex_t mutx;

namespace metric
{
const int MAX = 5;
int timer;
}

void* increment(void*)
{
while(1)
{
pthread_mutex_lock(&mutx);
++metric::timer;
pthread_mutex_unlock(&mutx);
}
return NULL;
}

void* counter(void*)
{
while(1)
{
if(metric::timer == metric::MAX)
{
cout << "re-setting timer value . . .\n";
pthread_mutex_lock(&mutx);
metric::timer = 0;
pthread_mutex_unlock(&mutx);
}
}
return NULL;
}

int main()
{
pthread_t Thread1, Thread2;

pthread_create(&Thread1, NULL, increment, NULL);
pthread_create(&Thread2, NULL, counter, NULL);

pthread_join(Thread1, NULL);
pthread_join(Thread2, NULL);

return 0;
}

closed account (o1vk4iN6)
There's no guarantee that your comparison will check for every increment of the timer. The increment() thread might run twice or more before you actually check the comparison in the counter() thread. So you could very well skip over the max.
Topic archived. No new replies allowed.