Optimization of pthread_mutex_lock in the application code

Hi,

I am using beagle Bone Black with debian image. Could any please suggest how to optimize the application code using pthread_mutex_lock. Let me describe the solution I am looking at.

For example, I have two thread sharing a global shared memory variable as below

thr_id1 = pthread_create ( &p_thread1, NULL, (void *)execution_task1, NULL );

thr_id2 = pthread_create ( &p_thread2, NULL, (void *)execution_task2, NULL );

void execution_task1()

{

for(int i = 0;i < 100;i++)

{
pthread_mutex_lock(&lock);

shmPtr->status = 1;

pthread_mutex_unlock(&lock);
sleep(1/2);

}

}

Why would you optimize the mutex ?

sleep(1/2); ==> doesn’t work , because 1/2 is cast to 0.

Sorry I did not finish the thing and got posted accidentally

For example, I have two thread sharing a global shared memory variable as below. The variable shmPtr->status is protected with mutex lock in both the function. Though there is a sleep(1/2) between mutex lock inside “for loop” in the task1 function , I could not access the shmPtr->status in task2 when required and have to wait until “for loop” exit in the task1 function, this takes around 50 seconds to take control of shmPtr->status by the task2 function.

I am wondering why the task1 function is not releasing the mutex lock even with an sleep(1/2).

thr_id1 = pthread_create ( &p_thread1, NULL, (void *)execution_task1, NULL );

thr_id2 = pthread_create ( &p_thread2, NULL, (void *)execution_task2, NULL );

void execution_task1()

{
for(int i = 0;i < 100;i++)

{
//100 lines of application code running here
pthread_mutex_lock(&lock);

shmPtr->status = 1; //shared memory variable

pthread_mutex_unlock(&lock);
sleep(1/2);

}

}

void execution_task2()

{
//100 lines of application code running here
pthread_mutex_lock(&lock);

shmPtr->status = 0; //shared memory variable

pthread_mutex_unlock(&lock);
sleep(1/2);

}

Regards,
NK

It’s not the best place to discuss this topic here …

have a look here:

https://stackoverflow.com/questions/6460542/performance-of-pthread-mutex-lock-unlock

Thank you, Like you said sleep(1/2) won’t work, then how to give a sleep of 500ms.

Regards,
NK

Usleep function… Google! Best place to find your answer!

Since "1/2" is integer division, the result is the same as sleep(0) --
which may return immediately and locking the mutex before the other thread
can even start.

  Providing a minimum compilable example demonstrating the problem would
also be of assistance. As it is we are left with either trying to write a
working program for testing, or working theoretically...