View Full Version : Threads
choisum
04-10-2007, 10:17 AM
Are there any mechanisms for thread synchronisation in PalmOS?
Is PalmOS pre-emptive? If not, it should be possible to set a flag in one thread and read it in another.
Edit:
To add some colour -- I'm looking at playing a sound stream synchronously -- can't use SndPlayResource :(
Alphasmart User
08-09-2008, 12:32 PM
You can use feature memory for flagging. Palm OS is preemptive, (in OS 4, I don't know about OS 5) and even in OS 4 it seems like you need to call SysTaskDelay();, otherwise the PalmOS hangs... You can use SysAppLaunchFlagNewThread for thread creation http://www.flippinbits.com/twiki/index.php?page=how-to-do-threads
dmitrygr
08-09-2008, 01:30 PM
1. do not use SysAppLaunchFlagNewThread in OS 3 and below
2. do not use SysAppLaunchFlagNewThread is OS 5 and above
3. sound threads are ok to use.
4. synchronization primitives exist in arm only, technically. They do not exist in 68k. But you can do it in 68k too. The idea is simple. When you grab memory semaphore, no tasks witching happens until you release it, so you can do something like this:
typedef volatile char* Mutex;
Mutex mutexCreate(){
char* res = MemPtrNew(sizeof(char));
*res = 0;
return res;
}
Boolean mutexTakeWithTimout(Mutex mutex,Int32 timeout /* in ticks */){
UInt32 endTime = TimGetTicks() + timeout;
do{
MemSemaphoreReserve(true);
if(!*mutex){
*mutex = 1;
MemSemaphoreRelease(true);
return true;
}
MemSemaphoreRelease(true);
SysTaskDelay(1);
}while(TimGetTicks() < endTime);
return false;
}
void mutexTake(Mutex mutex){ //take mutex unconditionally. block till success
while(!mutexTakeWithTimout(mutex,0x00FFFFFF));
//long timeout equivalent to never timing out
//even if it does time out, we'll retry with the while loop :)
}
void mutexPut(Mutex mutex){
*mutex = 0;
}
void mutexDestroy(Mutex mutex){
mutexTake(mutex);
MemPtrFree(mutex);
}
using it is simple
first create a mutex
Mutex myMutex = mutexCreate();
then pass it to all code that needs to synchronize, as needed. It is allowed to create copies of the mutex, like so
Mutex copy2 = myMutex
this is valid and will still work.
lock and unlock mutex with
//lock it normally. This code will block till it succeeds
mutexTake(myMutex);
//unlock it
mutexPut(myMutex);
//lock it with timout
if(!mutexTakeWithTimout(mymutex,TimTicksPerSecond())){
SysFatalAlert("Failed to acquire mutex for a whole second!");
}
and at the end of the app delete it to avoid leaking memory
mutexDestroy(myMutex);
On top of this you can build any other synchronization primitives you need.
vBulletin v3.0.3, Copyright ©2000-2012, Jelsoft Enterprises Ltd.