I am trying multi-core programming, to implement **Mutex** semaphore for :
**Initialization; Request ownership; Release ownership; Try ownership; Destruction .** 

I've created 3 threads. Each thread operates on a global variable Answer. 9 out of 10 times threads execute sequentially. But sometimes thread 3 didn't execute. Is 2nd threads mutex didn't release ?

Here's My Code: thread\_tasks.cc

```
void *task1(void *X)
{

    int MValue = pthread_mutex_init(&Mutex,NULL); //Initialization
    pthread_mutex_lock(&Mutex); //Request ownership
    Answer = Answer * 32; //critical section
    pthread_mutex_unlock(&Mutex); //Release ownership
    flag1=1;
    cout << "\nthread A Answer = " << Answer << endl;
    cout<<"\nthread 1 executed successfully";
}

 void *task2(void *X)
 {
    if(flag1==1)
 {
    int RC = pthread_mutex_trylock(&Mutex); //Try ownership
    cout<<"\nRC: "<<RC;
    Answer = Answer/2;
    flag2=1;
    cout<<"\nthread 2 executed successfully";
    pthread_mutex_unlock(&Mutex); //Release ownership
    pthread_mutex_destroy(&Mutex); //Destruction

}
}

void *task3(void *X)
{
    Answer = Answer+5;
    cout<<"\nthread 3 executed successfully";
}

```

Header file: thread\_tasks.h

```
using namespace std;
#include <iostream>
#include <pthread.h>

void *task1(void *X);
void *task2(void *X);
void *task3(void *X);

```

mutex\_example.cpp

```
int Answer = 10;
int flag1 = 0;
int flag2 = 0;
int main(int argc, char *argv[])
{

 pthread_t ThreadA, ThreadB, ThreadC;

 cout << "Answer = " << Answer << endl;
 pthread_create( &ThreadA,NULL,task1,NULL);
 pthread_create( &ThreadB,NULL,task2,NULL);
 pthread_create( &ThreadC,NULL,task3,NULL);
 pthread_join(ThreadA,NULL);
 pthread_join(ThreadB,NULL);
 pthread_join(ThreadC,NULL);

 cout << "Answer = " << Answer << endl;

 return(0);
}

```