Information Technology Reference
In-Depth Information
//Attempttoinsertanitem.Returntrueonsuccess.
//Ifthequeueisfull,returnfalse.
bool
TSQueue::tryInsert(intitem)
{
boolret=false;
lock.Acquire();
if(nFull<MAX){
items[nextEmpty]=item;
nFull++;
nextEmpty=(nextEmpty+1)%MAX;
ret=true;
constintMAX=10;
classTSQueue{
//Synchronizationvariables
Locklock;
}
lock.Release();
returnret;
//Statevariables
intitems[MAX];
intnFull;
intfirstFull;
intnextEmpty;
}
//Attempttoremoveanitem.Returntrueonsuccess.
//Ifthequeueisempty,returnfalse.
bool
TSQueue::tryRemove(int*item)
{
public:
TSQueue();
~TSQueue(){};
booltryInsert(intitem);
booltryRemove(int*item);
boolret=false;
lock.Acquire();
if(nFull>0){
*item=items[firstFull];
nFull--;
firstFull=(firstFull+1)%MAX;
ret=true;
}
lock.Release();
returnret;
}
Code from TSQueue.h
Code from TSQueue.cc
Figure5.3: The class definition for a simple shared object (a thread-safe
queue.)
cases. For example, if a thread holding a lock never releases it, other threads
can't make progress, so the bounded waiting condition is dened in terms of
successful acquire() operations.
Non-property: Thread ordering. The bounded waiting fairness property
defined above for locks is very weak. It guarantees that eventually a thread will
get a chance to acquire the lock, but it does not, for example, promise that the
threads will acquire the lock in FIFO order.
5.3.2
Locks and shared objects
As in standard object oriented programming, each shared object is an instance
of a class that denes the class's state and the methods that operate on that
state.
That state includes both state variables (e.g., ints, floats, strings, arrays, and
Search WWH ::




Custom Search