Example showing ARIA's cross-platform threading tools.ARIA provides some tools for writing multithreaded programs. These are abstractions of the threading library provided by the native operating system.
The three main tools are:
-
ArASyncTask a class which can run a method in a new thread
-
ArMutex, an object that can be shared by multiple threads to provide mutual exclusion from other shared data.
-
ArCondition, an object that can cause a thread to block execution until signaled by another thread to continue.
This example program shows the use of all three, with two threads interacting: the program's main thread of execution, and a new thread created using ArASyncTask. An ArMutex object is used to keep use of some shared data safe, and then the use of ArCondition is shown.
Threading can be error-prone, since any (perhaps subconcious) assumptions you have about the linear execution of code may not apply to simultaneous threads. Furthermore, different computers will execute multithreaded code in different ways (especially if they have different numbers of CPUs). ARIA's threading tools can help make multiple threads work, and help make multithreaded code portable, but you must always think carefully about how code might execute (including error conditions!) to avoid deadlocks and race conditions.
#include "Aria.h"
{
int myCounter;
public:
ExampleThread() : myCounter(0)
{
myCondition.
setLogName(
"ExampleThreadCondition");
}
{
{
myCounter++;
if(myCounter % 10 == 0)
{
}
}
return NULL;
}
void waitOnCondition()
{
}
int getCounter() { return myCounter; }
void setCounter(int ctr) { myCounter = ctr; }
void lockMutex() { myMutex.
lock(); }
void unlockMutex() { myMutex.
unlock(); }
};
int main()
{
ExampleThread exampleThread;
exampleThread.runAsync();
while(true)
{
exampleThread.lockMutex();
int c = exampleThread.getCounter();
exampleThread.unlockMutex();
printf("Main thread: Counter=%d.\n", c);
if(c >= 10)
break;
}
exampleThread.waitOnCondition();
ArLog::log(
ArLog::Normal,
"Main thread: Condition was signaled, and execution continued. Telling the other thread to stop running.");
exampleThread.stopRunning();
do {
} while(exampleThread.getRunningWithLock());
return 0;
}