线程手册
Additionally to creating jobs ( 作业手册 ) it is possible to create custom threads. Such custom threads can run in parallel to the main thread to perform various operations.
A custom thread is defined by implementing a custom class based on maxon::ThreadInterfaceTemplate :
// This example shows a simple thread implementation. The thread calculates pi; // the longer the thread runs, the more accurate the result will be.// This thread calculates pi until it is cancelled. // The longer the thread runs, the more precise the result will be. class CalculatePiThread : public maxon::ThreadInterfaceTemplate <CalculatePiThread> { public : ~CalculatePiThread() { _totalPointCount = 0; _insidePointCount = 0; }
// worker maxon::Result<void> operator ()() { // init random number generator maxon::LinearCongruentialRandom<maxon::Float32> random; random. Init (0);
// calculate pi until the thread is stopped while (! IsCancelled ()) { // check if random point is inside the unit-circle maxon::Vector2d64 point; point. x = random. Get01 (); point. y = random. Get01 (); if (point. GetSquaredLength () < 1.0) ++_insidePointCount;
// maximum number of points that can be handled with Int reached // stop thread if ( MAXON_UNLIKELY (_totalPointCount == maxon::LIMIT<maxon::Int>::MAX )) 取消 (); } return maxon::OK ; }
// Returns the calculated value of pi or an error if no calculation has happened yet. maxon::Result<maxon::Float> GetPI() { if (_totalPointCount == 0) return maxon::IllegalStateError( MAXON_SOURCE_LOCATION , "Thread has not calculated anything yet." _s);
An instance of a custom thread is typically stored as a global static variable:
// This example defines a global static variable to store the custom thread. static maxon::ThreadRefTemplate<CalculatePiThread> g_calculatePiThread;Custom threads are based on maxon::ThreadInterface and maxon::JobInterface . maxon::ThreadInterface functions are:
Further static utility functions are: