20 # pragma warning(push) 21 # pragma warning( disable: 4275 ) // warning C4275: non dll-interface class 44 #define ENABLE_VERBOSE_THREAD_TIMELINE 0 47 #define AGX_MAX_NUM_THREADS 1024 149 inline bool joinable();
154 inline unsigned int getThreadState();
178 static std::thread::native_handle_type getCurrentThreadHandle();
188 std::mutex m_handleMutex;
242 Index getIndex()
const;
254 static std::string getCurrentThreadDescription();
259 static Thread *getThread(
size_t id);
264 static Thread *getMainThread();
270 static void makeCurrentThreadMainThread();
276 static Thread *registerAsAgxThread();
282 static void unregisterAsAgxThread();
289 RandomGenerator& getRandomGenerator();
295 static bool isMainThread();
303 static bool isShuttingDown();
307 static void setEnableJobTimeline(
bool flag);
308 static bool getEnableJobTimeline();
318 void reportSystemJob(
320 const char* description,
321 const char* extraDataTitle =
nullptr,
327 Real getOverheadTime()
const;
332 void resetOverheadTime();
352 static void initThreadSystem();
355 static void exportAllTimelines();
357 static void flushTimelineLogs();
365 static ThreadStorageKey allocatePerThreadStorage();
367 static ThreadStorageData readPerThreadStorage( ThreadStorageKey key );
369 static void writePerThreadStorage( ThreadStorageKey key, ThreadStorageData data);
371 static void freePerThreadStorage( ThreadStorageKey key );
374 static int log(
const char *format, ...);
375 static void flushLogs();
381 static void addTask(
Task *task);
401 class MainThreadSingleton;
402 static Thread *initMainThread();
404 static void performNumThreadsChange();
405 void startWaitTimer();
406 void stopWaitTimer();
410 void freeDefaultStorages();
411 void spawn(
Job *job);
412 void sortInsertJob(
Job *job);
415 void completeFrame(
Task *task);
417 bool isActive()
const;
420 template <
bool THREAD_TIMELINE_STATISTICS>
424 void blockingDoWork();
427 void wakeupThreads();
428 void pushTargetJob(
Thread *target,
Job *job,
bool activateTarget =
true);
429 static void taskCompleted(
Task *task);
434 Job *getExecutionJob();
444 char *m_currentPathString;
446 Notify::ThreadData *getNotifyData();
461 static const UInt32 mod = ((1ULL << 32) - 5);
462 static const UInt32 mul = 69070U;
470 FastRandom m_fastRandom;
474 inline Frame(
Task *t =
nullptr) : task(t), done(false) {}
475 inline Frame& operator=(
const Frame& other) {task = other.task; done = other.done.load();
return *
this;}
477 std::atomic<bool> done;
480 #define AGX_THREAD_FRAME_STACK_MAX_DEPTH 64 483 size_t m_activationDepth;
484 std::atomic<Int32> m_activationCount;
486 Thread *m_listNodeNext;
495 return lhs->getCostEstimate() < rhs->getCostEstimate();
499 typedef std::priority_queue<Job *, agx::Vector<Job *>, JobCompare> JobQueue;
500 JobQueue m_sharedJobs;
514 std::atomic<bool> m_running;
518 std::atomic<Int32> m_pushCounter;
523 Timer m_overheadTimer;
525 Real m_totJobProcessTime;
526 Real m_totJobOverheadTime;
527 int m_totJobElements;
528 Real m_startupTimestamp;
529 Real m_shutdownTimestamp;
534 static Thread *s_mainThread;
535 static Thread *s_mainWorkThread;
536 static Thread *s_ioThread;
537 static Callback1<Task *> s_taskCompletionCallback;
540 std::random_device m_randomDevice;
541 std::mt19937 m_mersienneTwister;
545 template <
typename T>
546 T *allocateLocalVector(LocalVector<T> *buffer);
548 template <
typename T>
549 void deallocateLocalVector(LocalVector<T> *buffer);
555 void registerContainerAllocation(
Container *container);
556 void unregisterContainerAllocation(
Container *container);
557 void *allocateScratchPadBuffer(
size_t numBytes);
558 void deallocateScratchPadBuffer(
void *buffer,
size_t numBytes);
560 struct ScratchPadArea
562 ScratchPadArea() : buffer(nullptr),
end(nullptr), head(nullptr), m_allocator(
"ScratchPad")
565 ~ScratchPadArea() { m_allocator.deallocateBytes(buffer); }
574 ScratchPadArea m_scratchPad;
577 static bool s_enableJobTimeline;
580 static std::exception_ptr s_unhandledException;
583 struct LocalTimelineEntry
593 , extraDataTitle(nullptr)
597 enum JobType { PRE, DISPATCH, POST,
UNKNOWN };
608 const char* extraDataTitle;
617 void exportTimelineEntries();
618 void reportTimelineJob(
Job *job);
619 void pushTimelineEntry(
const LocalTimelineEntry& entry);
625 LogChunk(
size_t numBytes);
630 size_t numAvailable();
639 LogEntry(
agx::UInt64 timestamp_,
const char* message_);
644 int logImplementation(
const char* format, va_list ap);
645 static int cmpLogEntry(
const LogEntry& entry1,
const LogEntry& entry2);
651 DefaultStorageTable m_defaultStorageTable;
656 static ThreadStorageKey s_threadObject_key;
670 inline bool BasicThread::joinable()
672 return m_handle.joinable();
677 inline unsigned int BasicThread::getThreadState()
679 return m_state.load();
692 return s_threads[
id];
700 return static_cast<Thread*
>( Thread::readPerThreadStorage(s_threadObject_key) );
712 return s_mainWorkThread;
717 AGX_FORCE_INLINE bool Thread::isActive()
const {
return m_activationCount.load() > 0; }
727 m_waitTime += (
Real)m_timer.getTime();
732 return m_mersienneTwister;
738 inline int Thread::log(
const char *format, ...)
741 va_start(arguments, format);
751 return m_byteAllocator.allocate(numBytes);
756 m_byteAllocator.deallocateBytes(ptr);
759 template <
typename T>
762 return this->getPool<T>()->allocate();
765 template <
typename T>
768 this->getPool<T>()->deallocate(ptr);
772 template <
typename T>
775 return this->getPool<T>()->create();
778 template <
typename T>
781 this->getPool<T>()->destroy(ptr);
784 template <
typename T>
787 uint32_t
id = agxData::getType<T>()->getId();
788 if (
id >= m_pools.size())
789 m_pools.resize(
id+1, 0);
797 void setCurrentConstructionObject(
void *ptr);
798 void *getCurrentConstructionObject();
808 if (m_scratchPad.head + numBytes > m_scratchPad.end)
810 size_t currentSize = m_scratchPad.end - m_scratchPad.buffer;
811 const Real growFactor = 1.5;
812 size_t newSize = (size_t)(
Real(currentSize + numBytes) * growFactor );
815 char *newBuffer = (
char *)m_scratchPad.m_allocator.allocateBytes(newSize, 64);
816 agxAssertN(newBuffer,
"Thread %d could not allocate %u bytes for job scratch pad!", this->getId(), (
unsigned)newSize);
821 size_t numUsed = m_scratchPad.head - m_scratchPad.buffer;
824 memcpy(newBuffer, m_scratchPad.buffer, numUsed);
826 m_scratchPad.m_allocator.deallocateBytes(m_scratchPad.buffer);
829 for (
size_t i = 0; i < m_scratchPad.m_activeAllocations.size(); ++i)
831 Container *container = m_scratchPad.m_activeAllocations[i];
835 ptrdiff_t offset = (
char *)container->
m_buffer - (
char *)m_scratchPad.buffer;
836 container->
m_buffer = newBuffer + offset;
840 m_scratchPad.buffer = newBuffer;
841 m_scratchPad.end = m_scratchPad.buffer + newSize;
842 m_scratchPad.head = m_scratchPad.buffer + numUsed;
845 void *mem = m_scratchPad.head;
846 m_scratchPad.head += numBytes;
851 AGX_FORCE_INLINE void Thread::deallocateScratchPadBuffer(
void *buffer,
size_t numBytes)
853 agxAssert(!buffer || (buffer >= m_scratchPad.buffer && buffer < m_scratchPad.end));
855 if ((
char *)buffer + numBytes == m_scratchPad.head)
856 m_scratchPad.head = (
char *)buffer;
861 m_scratchPad.m_activeAllocations.push_back(container);
870 agxAssert1(!m_scratchPad.m_activeAllocations.empty() && container == m_scratchPad.m_activeAllocations.back(),
"LIFO order required!");
871 m_scratchPad.m_activeAllocations.pop_back();
874 if (m_scratchPad.m_activeAllocations.empty())
875 m_scratchPad.head = m_scratchPad.buffer;
881 #if ENABLE_VERBOSE_THREAD_TIMELINE 882 #define AGX_BEGIN_TIMELINE_REPORT(variable) \ 883 auto variable ## _begin_time = agx::Timer::getCurrentTick() 885 #define AGX_END_TIMELINE_REPORT(variable, title) \ 886 auto variable ## _end_time = agx::Timer::getCurrentTick(); \ 887 agx::Thread::getCurrentThread()->reportSystemJob( variable ## _begin_time , variable ## _end_time, title); 889 #define AGX_END_TIMELINE_REPORT_DATA(variable, title, title2, data) \ 890 auto variable ## _end_time = agx::Timer::getCurrentTick(); \ 891 agx::Thread::getCurrentThread()->reportSystemJob( variable ## _begin_time , variable ## _end_time, title, title2, data) 893 #define AGX_BEGIN_TIMELINE_REPORT(variable) 894 #define AGX_END_TIMELINE_REPORT(variable, title) 895 #define AGX_END_TIMELINE_REPORT_DATA(variable, title, title2, data) 900 # pragma warning(pop) Basic wrapper class aroud std::thread.
void AGXPHYSICS_EXPORT init()
Initialize agx.
void AGXPHYSICS_EXPORT shutdown()
Shutdown agx.
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.
Namespace agx 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.
GLenum GLuint GLenum GLsizei const GLchar * message
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