trylockmutex always fails..

BlitzMax Forums/BlitzMax Programming/trylockmutex always fails..

Rozek(Posted 2010) [#1]
Hello!

I just ran into the problem that "trylockmutex" always returns false although

- there is no other thread yet which could have locked the mutex and
- all "lockmutex" (and other "trylockmutex") calls have been commented out (I just double checked that)

Thus, NO thread has been able (yet) to lock the Mutex - but "trylockmutex" still fails (i.e. returns false)

[added]
I just created a new Mutex and tried to "trylockmutex" it - and (guess what?) failed! I.e.,
local Mutex:TMutex = createMutex()
if (tryLockMutex(Mutex)) then
  writestdout("Yeah - it worked!")
end if

will never print the message...
[/added]

[added]
and...YES...I DID build a threaded executable (I have other Mutexes which work fine using "lockMutex"/"unlockMutex" - but here, I need "tryLockMutex"!)
[/added]

Does anybody have any idea?

I am using BlitzMAX 1.38 with MaxGUI 1.39 on a Mac mini Intel running Mac OS X 10.4.11

Thanks in advance for any hints!


Rozek(Posted 2010) [#2]
Here is a complete sample program which illustrates the problem

superstrict 

local Mutex:TMutex = createMutex()
local Result:int = tryLockMutex(Mutex)
if (Result) then
  writestdout("Yeah - it worked! (Result = " + Result + ")")
else
  writestdout("Damn - it failed! (Result = " + Result + ")")
end if



Rozek(Posted 2010) [#3]
Well, I guess I got it!

Using the following code to "play around" with "trylockmutex" et al.
superstrict 

global Mutex:TMutex = createMutex()

  global ThreadLocker:TSemaphore = createSemaphore(0)

  function ThreadFunction:Object (Data:Object)
    debuglog("Subthread:  started")
      lockMutex(Mutex)
    debuglog("Subthread:  locked Mutex")

    debuglog("Subthread:  now waiting forever")
    waitSemaphore(ThreadLocker)
    debuglog("Subthread:  stopping")
  end function

local Result:int
'Result = tryLockMutex(Mutex)
'debuglog("MainThread: tryLockMutex yields " + Result)

debuglog("MainThread: spawning Subthread")
local Subthread:TThread = createThread(ThreadFunction,null)

  delay(1000)

debuglog("MainThread: about to tryLockMutex again")
Result = tryLockMutex(Mutex)
debuglog("MainThread: tryLockMutex yields " + Result)

I found out that (under Mac OS X, at least):

- trylockmutex basically works, but
- trylockmutex yields 0 on success(!) and
- trylockmutex yields something <> 0 on failure (i.e. when it could not lock the mutex)

I still have to check what happens under Win32 (and Linux), but under MacOS X this knowledge allows for a simple "workaround"!