Since some languages don't offer mutex lock, one will need to build it by one's self. I usually write some code like this: (pseudo-C++, just to let you know what I mean. I'm not sure whether my writing is correct as I haven't written C++ code in years)
oldval = 0;
newval = 1;
//suggest there was a Compare And Set operation that make only one thread return true,if no CAS operation , call any other language module that can offer a cas instead
while (!CAS(*somepointer,oldval,newval)) {
//lock failed
sleep(1000); //sleep one second or some value really depend on what you are doing.
}
//lock succeed, do something....
*somepointer = oldval; //release lock.
Obviously sleep
will lower the speed of processing, but I used to worry about, if sleep
is discarded... wouldn't threads switching too frequently and lower the performance? Now that I think deeper, how is sleep
implemented? If they do something like this...
expired = getCurrentTime() + sleepTime;
while (getCurrentTime() < expired) { }
... this would only get things worse.
Now I think sleep
should only be used if I really need to suspend the thread for a while, so maybe my case is just wrong.