Hi all! I got a problem regarding POSIX threads specifically pthread_mutex_lock and pthread_mutex_unlock.
Here is the code:
Ok. Try running the code above.
I was expecting to see an output similar to the one below: (an incrementing value)
But instead, what got are all zeros.
Can someone help me out?
Thanks!
Rome did not create a great empire by having meetings, they did it by
killing all those who opposed them.
- janvier -
Here is the code:
Code:
#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;
void* doRunA(void* arg);
class A
{
public:
A() : a(0) { }
void Run()
{
pthread_t thr1;
pthread_create(&thr1, reinterpret_cast<pthread_attr_t*>(0), doRunA, this);
pthread_detach(thr1);
}
void IncrementA()
{
pthread_mutex_lock(&mut);
this->a++;
pthread_mutex_unlock(&mut);
// sleep(5);
}
void ShowA()
{
cout << "Value of a = " << this->a << endl;
}
private:
int a;
pthread_mutex_t mut;
};
void* doRunA(void* arg)
{
A* pA = reinterpret_cast<A*>(arg);
while(true)
pA->IncrementA();
}
int main(int argc, char** argv)
{
A myA;
myA.Run();
while(true)
myA.ShowA();
return 0;
}
Ok. Try running the code above.
I was expecting to see an output similar to the one below: (an incrementing value)
Code:
Value of a = 0;
Value of a = 1;
Value of a = 2;
...
...
But instead, what got are all zeros.
Code:
Value of a = 0;
Value of a = 0;
Value of a = 0;
...
...
Can someone help me out?
Thanks!
Rome did not create a great empire by having meetings, they did it by
killing all those who opposed them.
- janvier -