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:
- I defined a global variable is_mutex_locked (done at the beginning)
- 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.