[4.30b3,4.20] Killing thread mutex trap with unlock key ;-)
Posted: Tue Oct 21, 2008 6:15 pm
I played around with threads a bit and stumbled on something I almost considered a bug.
When a thread ends or is killed, it will not unlock any mutex it might have locked.
As the thread is killed before it has any chance to unlock the mutex via explicit user code, the main program can not lock it for itself.
Seeing only that, I considered, that a thread should unlock all mutexes it has locked when it ends, either normally or by being killed.
However the mutex seems to work differently than I thought it would.
When you uncomment the line with "UnlockMutex(myMutex)" in the main progam, it can suddenly lock the mutex again.
So can any thread or the main program simply unlock any mutex, no matter if it was not locked by itself
Is there any way to know, "who" locked a mutex?
When I kill a thread and want to enshure, it has not left any mutex locked, I could try to unlock it by the killing main.
But how then would I know if the mutex was not locked rightfully by some other thread?
Is this somehow covered by PureBasic, or should I simply build my own infrastuctur for that?
When a thread ends or is killed, it will not unlock any mutex it might have locked.
Code: Select all
Global myThread.l
Global myMutex.l
Procedure ThreadProc(*Dummy)
; ...
LockMutex(myMutex)
Delay(1000)
UnlockMutex(myMutex)
;
EndProcedure
; try to get the mutex locked with timeout
Procedure GetMutexTm()
Protected lngMaxRuns.l = 20 ; 20 x 100 ms = 2 secs.
Protected lngRuns.l
lngRuns = 0
While Not TryLockMutex(myMutex)
Delay(100)
lngRuns + 1
If lngRuns > lngMaxRuns
Debug "Timeout waiting for mutex"
ProcedureReturn #False
EndIf
Wend
ProcedureReturn #True
EndProcedure
myMutex = CreateMutex()
myThread = CreateThread(@ThreadProc(), 1)
Delay (500)
KillThread(myThread)
Delay (200)
;UnlockMutex(myMutex)
If GetMutexTm()
Debug "got the mutex locked :-)"
Else
Debug "could not lock the mutex :-("
EndIf
Debug "The end."
Seeing only that, I considered, that a thread should unlock all mutexes it has locked when it ends, either normally or by being killed.
However the mutex seems to work differently than I thought it would.
When you uncomment the line with "UnlockMutex(myMutex)" in the main progam, it can suddenly lock the mutex again.
So can any thread or the main program simply unlock any mutex, no matter if it was not locked by itself
Is there any way to know, "who" locked a mutex?
When I kill a thread and want to enshure, it has not left any mutex locked, I could try to unlock it by the killing main.
But how then would I know if the mutex was not locked rightfully by some other thread?
Is this somehow covered by PureBasic, or should I simply build my own infrastuctur for that?