mutex mistakes i made (2)

We need a mutex for protecting the access to a hardware block.

Two conditions:

— the hardware block is shared by multiple processes.

— Each operation performed on this hardware block  typically lasts for 2 ms.

Therefore, the mutex is initialized as a shared object, /dev/shmem, and my code look like:

main_thread()

{

start a new operation;

}

dedicated_thread()

{

Wait for “operation completion” interrupt with a timeout;

if the user wants to stop, if is_mutex_locked == 1, unlock the mutex, and exit.

When interrupt comes, if is_mutex_locked == 1, unlock the mutex;

If enough buffers,

lock the mutex, and set is_mutex_locked to 1,

Set up the next operation.

}

Signal_thread()

{

listen to signals;

if it is signal asking for stop,

Wait for the operation complete (by reading a DMA status register); if is_mutex_locked == 1, unlock the mutex

Tell the dedicated thread to exit (by setting a global variable g_dead).

Wait for the dedicated thread exit;

}

There are other two changes:

  1. I defined a global variable is_mutex_locked (done at the beginning)
  2. unlock the mutex after waiting for the operation complete..(done as the last step)

Since #2 is added, everything goes weired. another process is able to lock the mutex when the previous process is still using it, the mutex never gets unlocked…

where is the problem: main thead executes a void, useless pthread_mutex_unlock() while waiting for completion, which leads to dedicted_thread() doesn’t do any unlocking before exit.

mutex: a mistake I made

I defined a shared mutex for processes, in /dev/shmem

The mutex is for protecting the access to a hardware block. Each operation might last for 2 ms.

Dedicated_thread()

{

Wait for “operation completion” interrupt.

When interrupt comes, unlock the mutex;

(if the user wants to stop, unlock the mutex).

If required,

Lock the mutex,

Set up the next operation.

}

I wanted to only unlock the mutex if it was being locked, therefore, I add some check, an global_variable is_mutex_locked.

Don’t use global variable to indicate if the mutex is locked, or unlock it.

Stop_operation()

{

Wait for the operation complete (by reading a DMA status register);

Tell the dedicated thread to exit (by setting a global variable g_dead).

Wait for the dedicated thread exit;

}