20 # pragma warning(push) 21 # pragma warning( disable: 4275 ) // warning C4275: non dll-interface class 22 # pragma warning(disable: 4251) // warning C4251: class X needs to have dll-interface to be used by clients of class Y 45 #define ENABLE_VERBOSE_THREAD_TIMELINE 0 48 #define AGX_MAX_NUM_THREADS 1024 150 inline bool joinable();
155 inline unsigned int getThreadState();
179 static std::thread::native_handle_type getCurrentThreadHandle();
189 std::mutex m_handleMutex;
243 Index getIndex()
const;
255 static std::string getCurrentThreadDescription();
260 static Thread *getThread(
size_t id);
265 static Thread *getMainThread();
271 static void makeCurrentThreadMainThread();
277 static Thread *registerAsAgxThread();
283 static void unregisterAsAgxThread();
290 RandomGenerator& getRandomGenerator();
296 static bool isMainThread();
304 static bool isShuttingDown();
308 static void setEnableJobTimeline(
bool flag);
309 static bool getEnableJobTimeline();
319 void reportSystemJob(
321 const char* description,
322 const char* extraDataTitle =
nullptr,
328 Real getOverheadTime()
const;
333 void resetOverheadTime();
353 static void initThreadSystem();
356 static void exportAllTimelines();
358 static void flushTimelineLogs();
366 static ThreadStorageKey allocatePerThreadStorage();
368 static ThreadStorageData readPerThreadStorage( ThreadStorageKey key );
370 static void writePerThreadStorage( ThreadStorageKey key, ThreadStorageData data);
372 static void freePerThreadStorage( ThreadStorageKey key );
375 static int log(
const char *format, ...);
376 static void flushLogs();
382 static void addTask(
Task *task);
402 class MainThreadSingleton;
403 static Thread *initMainThread();
405 static void performNumThreadsChange();
406 void startWaitTimer();
407 void stopWaitTimer();
411 void freeDefaultStorages();
412 void spawn(
Job *job);
413 void sortInsertJob(
Job *job);
416 void completeFrame(
Task *task);
418 bool isActive()
const;
421 template <
bool THREAD_TIMELINE_STATISTICS>
425 void blockingDoWork();
428 void wakeupThreads();
429 void pushTargetJob(
Thread *target,
Job *job,
bool activateTarget =
true);
430 static void taskCompleted(
Task *task);
435 Job *getExecutionJob();
445 char *m_currentPathString;
447 Notify::ThreadData *getNotifyData();
462 static const UInt32 mod = ((1ULL << 32) - 5);
463 static const UInt32 mul = 69070U;
471 FastRandom m_fastRandom;
475 inline Frame(
Task *t =
nullptr) : task(t), done(false) {}
476 inline Frame& operator=(
const Frame& other) {task = other.task; done = other.done.load();
return *
this;}
478 std::atomic<bool> done;
481 #define AGX_THREAD_FRAME_STACK_MAX_DEPTH 64 484 size_t m_activationDepth;
485 std::atomic<Int32> m_activationCount;
487 Thread *m_listNodeNext;
496 return lhs->getCostEstimate() < rhs->getCostEstimate();
500 typedef std::priority_queue<Job *, agx::Vector<Job *>, JobCompare> JobQueue;
501 JobQueue m_sharedJobs;
515 std::atomic<bool> m_running;
519 std::atomic<Int32> m_pushCounter;
524 Timer m_overheadTimer;
526 Real m_totJobProcessTime;
527 Real m_totJobOverheadTime;
528 int m_totJobElements;
529 Real m_startupTimestamp;
530 Real m_shutdownTimestamp;
535 static Thread *s_mainThread;
536 static Thread *s_mainWorkThread;
537 static Thread *s_ioThread;
538 static Callback1<Task *> s_taskCompletionCallback;
541 std::random_device m_randomDevice;
542 std::mt19937 m_mersienneTwister;
546 template <
typename T>
547 T *allocateLocalVector(LocalVector<T> *buffer);
549 template <
typename T>
550 void deallocateLocalVector(LocalVector<T> *buffer);
556 void registerContainerAllocation(
Container *container);
557 void unregisterContainerAllocation(
Container *container);
558 void *allocateScratchPadBuffer(
size_t numBytes);
559 void deallocateScratchPadBuffer(
void *buffer,
size_t numBytes);
561 struct ScratchPadArea
563 ScratchPadArea() : buffer(nullptr),
end(nullptr), head(nullptr), m_allocator(
"ScratchPad")
566 ~ScratchPadArea() { m_allocator.deallocateBytes(buffer); }
575 ScratchPadArea m_scratchPad;
578 static bool s_enableJobTimeline;
581 static std::exception_ptr s_unhandledException;
584 struct LocalTimelineEntry
594 , extraDataTitle(nullptr)
598 enum JobType { PRE, DISPATCH, POST,
UNKNOWN };
609 const char* extraDataTitle;
618 void exportTimelineEntries();
619 void reportTimelineJob(
Job *job);
620 void pushTimelineEntry(
const LocalTimelineEntry& entry);
626 LogChunk(
size_t numBytes);
631 size_t numAvailable();
640 LogEntry(
agx::UInt64 timestamp_,
const char* message_);
645 int logImplementation(
const char* format, va_list ap);
646 static int cmpLogEntry(
const LogEntry& entry1,
const LogEntry& entry2);
652 DefaultStorageTable m_defaultStorageTable;
657 static ThreadStorageKey s_threadObject_key;
671 inline bool BasicThread::joinable()
673 return m_handle.joinable();
678 inline unsigned int BasicThread::getThreadState()
680 return m_state.load();
693 return s_threads[id];
701 return static_cast<Thread*
>( Thread::readPerThreadStorage(s_threadObject_key) );
713 return s_mainWorkThread;
718 AGX_FORCE_INLINE bool Thread::isActive()
const {
return m_activationCount.load() > 0; }
728 m_waitTime += (
Real)m_timer.getTime();
733 return m_mersienneTwister;
739 inline int Thread::log(
const char *format, ...)
742 va_start(arguments, format);
752 return m_byteAllocator.allocate(numBytes);
757 m_byteAllocator.deallocateBytes(ptr);
760 template <
typename T>
763 return this->getPool<T>()->allocate();
766 template <
typename T>
769 this->getPool<T>()->deallocate(ptr);
773 template <
typename T>
776 return this->getPool<T>()->create();
779 template <
typename T>
782 this->getPool<T>()->destroy(ptr);
785 template <
typename T>
788 uint32_t
id = agxData::getType<T>()->getId();
789 if (
id >= m_pools.size())
790 m_pools.resize(
id+1, 0);
798 void setCurrentConstructionObject(
void *ptr);
799 void *getCurrentConstructionObject();
809 if (m_scratchPad.head + numBytes > m_scratchPad.end)
811 size_t currentSize = m_scratchPad.end - m_scratchPad.buffer;
812 const Real growFactor = 1.5;
813 size_t newSize = (size_t)(
Real(currentSize + numBytes) * growFactor );
816 char *newBuffer = (
char *)m_scratchPad.m_allocator.allocateBytes(newSize, 64);
817 agxAssertN(newBuffer,
"Thread %d could not allocate %u bytes for job scratch pad!", this->getId(), (
unsigned)newSize);
822 size_t numUsed = m_scratchPad.head - m_scratchPad.buffer;
825 memcpy(newBuffer, m_scratchPad.buffer, numUsed);
827 m_scratchPad.m_allocator.deallocateBytes(m_scratchPad.buffer);
830 for (
size_t i = 0; i < m_scratchPad.m_activeAllocations.size(); ++i)
832 Container *container = m_scratchPad.m_activeAllocations[i];
836 ptrdiff_t offset = (
char *)container->
m_buffer - (
char *)m_scratchPad.buffer;
837 container->
m_buffer = newBuffer + offset;
841 m_scratchPad.buffer = newBuffer;
842 m_scratchPad.end = m_scratchPad.buffer + newSize;
843 m_scratchPad.head = m_scratchPad.buffer + numUsed;
846 void *mem = m_scratchPad.head;
847 m_scratchPad.head += numBytes;
852 AGX_FORCE_INLINE void Thread::deallocateScratchPadBuffer(
void *buffer,
size_t numBytes)
854 agxAssert(!buffer || (buffer >= m_scratchPad.buffer && buffer < m_scratchPad.end));
856 if ((
char *)buffer + numBytes == m_scratchPad.head)
857 m_scratchPad.head = (
char *)buffer;
862 m_scratchPad.m_activeAllocations.push_back(container);
871 agxAssert1(!m_scratchPad.m_activeAllocations.empty() && container == m_scratchPad.m_activeAllocations.back(),
"LIFO order required!");
872 m_scratchPad.m_activeAllocations.pop_back();
875 if (m_scratchPad.m_activeAllocations.empty())
876 m_scratchPad.head = m_scratchPad.buffer;
882 #if ENABLE_VERBOSE_THREAD_TIMELINE 883 #define AGX_BEGIN_TIMELINE_REPORT(variable) \ 884 auto variable ## _begin_time = agx::Timer::getCurrentTick() 886 #define AGX_END_TIMELINE_REPORT(variable, title) \ 887 auto variable ## _end_time = agx::Timer::getCurrentTick(); \ 888 agx::Thread::getCurrentThread()->reportSystemJob( variable ## _begin_time , variable ## _end_time, title); 890 #define AGX_END_TIMELINE_REPORT_DATA(variable, title, title2, data) \ 891 auto variable ## _end_time = agx::Timer::getCurrentTick(); \ 892 agx::Thread::getCurrentThread()->reportSystemJob( variable ## _begin_time , variable ## _end_time, title, title2, data) 894 #define AGX_BEGIN_TIMELINE_REPORT(variable) 895 #define AGX_END_TIMELINE_REPORT(variable, title) 896 #define AGX_END_TIMELINE_REPORT_DATA(variable, title, title2, data) 901 # pragma warning(pop) Basic wrapper class aroud std::thread.
void AGXPHYSICS_EXPORT init()
Initialize AGX Dynamics API including thread resources and must be executed before using the AGX API...
void AGXPHYSICS_EXPORT shutdown()
Shutdown of the AGX Dynamics API will be done when the number of shutdown matches the number of calls...
The Container is the base class for several of the container classes proided by AGX, such as agx::Vector and agx::HashSet.
agx::Thread is a representation of an OS specific implementation of a computational thread...
ThreadState
States for the thread.
Data storage for a collection of entity instances of a specified EntityModel.
An abstract job/workblock representation, which allows work threads to execute arbitrary tasks...
#define agxAssertN(expr, format,...)
#define AGX_MAX_NUM_THREADS
HashTable< Thread *, Index > ThreadIdTable
#define AGXPHYSICS_EXPORT
AGXCORE_EXPORT const InvalidIndexStruct InvalidIndex
#define AGX_DECLARE_POINTER_TYPES(type)
A representation of a generic task.
void agxFlushThreadLogs()
void AGXCORE_EXPORT resetStartTick()
Reset the startTick value to the current tick.
Block synchronization primitive.
Base class providing referencing counted objects.
VectorPOD< class Job * > JobPtrVector
agx::VectorPOD< Thread * > ThreadPtrVector
std::atomic< unsigned int > m_state
Vector containing 'raw' data.
The agx namespace contains the dynamics/math part of the AGX Dynamics API.
AGXCORE_EXPORT Thread * getCurrentThread()
Class for handling logging of messages.
Contains classes for low level data storage for AGX.
static bool immediateLogging
virtual void run()
This method is invoked by start.
An abstract description of a data entity stored using SOA (structure of arrays) pattern in a EntitySt...
pthread_key_t ThreadStorageKey
A UUID, or Universally unique identifier, is intended to uniquely identify information in a distribut...
void AGXCORE_EXPORT setNumThreads(size_t numThreads)
Set the number of threads to use (including the main thread).
Generator of UUID values based on V4 http://en.wikipedia.org/wiki/Universally_unique_identifier.
#define agxAssert1(expr, msg)
LinearProbingHashSetImplementation< KeyT, HashT >::iterator end(LinearProbingHashSetImplementation< KeyT, HashT > &set)
Inheritance with partial specialization due to bug with ref_ptr containers.
#define AGX_THREAD_FRAME_STACK_MAX_DEPTH
std::mt19937 RandomGenerator