Spinning Topp Logo BlackTopp Studios
inc
workunit.cpp
Go to the documentation of this file.
1 // The DAGFrameScheduler is a Multi-Threaded lock free and wait free scheduling library.
2 // © Copyright 2010 - 2016 BlackTopp Studios Inc.
3 /* This file is part of The DAGFrameScheduler.
4 
5  The DAGFrameScheduler is free software: you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation, either version 3 of the License, or
8  (at your option) any later version.
9 
10  The DAGFrameScheduler is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  GNU General Public License for more details.
14 
15  You should have received a copy of the GNU General Public License
16  along with The DAGFrameScheduler. If not, see <http://www.gnu.org/licenses/>.
17 */
18 /* The original authors have included a copy of the license specified above in the
19  'doc' folder. See 'gpl.txt'
20 */
21 /* We welcome the use of the DAGFrameScheduler to anyone, including companies who wish to
22  Build professional software and charge for their product.
23 
24  However there are some practical restrictions, so if your project involves
25  any of the following you should contact us and we will try to work something
26  out:
27  - DRM or Copy Protection of any kind(except Copyrights)
28  - Software Patents You Do Not Wish to Freely License
29  - Any Kind of Linking to Non-GPL licensed Works
30  - Are Currently In Violation of Another Copyright Holder's GPL License
31  - If You want to change our code and not add a few hundred MB of stuff to
32  your distribution
33 
34  These and other limitations could cause serious legal problems if you ignore
35  them, so it is best to simply contact us or the Free Software Foundation, if
36  you have any questions.
37 
38  Joseph Toppi - toppij@gmail.com
39  John Blackwood - makoenergy02@gmail.com
40 */
41 #ifndef _workunit_cpp
42 #define _workunit_cpp
43 
44 /// @file
45 /// @brief This file has the implementation of the @ref Mezzanine::Threading::DefaultWorkUnit.
46 
47 #include "workunit.h"
48 #include "systemcalls.h"
49 #include "atomicoperations.h"
50 #include "doublebufferedresource.h"
51 
52 #ifdef MEZZ_DEBUG
53 #include <cassert>
54 #endif
55 
56 namespace Mezzanine
57 {
58  namespace Threading
59  {
60  /////////////////////////////////////////////////////////////////////////////////////////////
61  // The Simple Stuff
62 
63  DefaultWorkUnit::DefaultWorkUnit(const DefaultWorkUnit&)
64  {}
65 
66  DefaultWorkUnit& DefaultWorkUnit::operator=(DefaultWorkUnit& Unused)
67  { return Unused; }
68 
70  {}
71 
73  {}
74 
75  /////////////////////////////////////////////////////////////////////////////////////////////
76  // Work with the dependents as in what must not start until this finishes.
77 
79  { return SchedulerToCount.GetDependentCountOf(this); }
80 
81  /////////////////////////////////////////////////////////////////////////////////////////////
82  // Work with the dependencies as in what must finish before we can run this work unit.
83 
85  { return Dependencies.at(Index); }
86 
88  { return Dependencies.size(); }
89 
91  {
92  Whole Results = Dependencies.size();
93  for(std::vector<iWorkUnit*>::const_iterator Iter=Dependencies.begin(); Iter!=Dependencies.end(); ++Iter)
94  { Results += (*Iter)->GetDependencyCount(); }
95  return Results;
96 
97  }
98 
100  { Dependencies.push_back(NewDependency); }
101 
103  {
104  Dependencies.erase(
105  std::remove(Dependencies.begin(),Dependencies.end(),RemoveDependency),
106  Dependencies.end()
107  );
108  }
109 
111  { Dependencies.clear(); }
112 
114  {
115  for (std::vector<iWorkUnit*>::iterator Iter = Dependencies.begin(); Iter!=Dependencies.end(); ++Iter)
116  {
117  if( Complete != (*Iter)->GetRunningState() )
118  { return false; }
119  }
120  return true;
121  }
122 
123  /////////////////////////////////////////////////////////////////////////////////////////////
124  // Work with the ownership and RunningState
126  {
128  { return NotStarted; }
129 
131  { return Starting; } // This is the only place a starting should be generated, and it is never placed in CurrentRunningState
132 
133  return NotStarted;
134  }
135 
137  { return (RunningState)CurrentRunningState; } // This only works because we set all of in RunningState to be unsigned.
138 
140  //{ while(CurrentRunningState!=AtomicCompareAndSwap(&CurrentRunningState,CurrentRunningState,NotStarted)); }
142 
143  /////////////////////////////////////////////////////////////////////////////////////////////
144  // Work with the performance log
146  { return PerformanceLog.GetAverage(); }
147 
149  { return PerformanceLog; }
150 
151  /////////////////////////////////////////////////////////////////////////////////////////////
152  // Deciding when to and doing the work
153 
155  {
157 
158  std::ostream& Out = CurrentThreadStorage.GetUsableLogger();
159  Out << "<WorkUnit id=\"" << std::hex << this << std::dec << "\">" << std::endl;
160  #ifdef MEZZ_DEBUG
161  Out << "<WorkUnitStart BeginTimeStamp=\"" << Begin << "\" ThreadID=\"" << Mezzanine::Threading::this_thread::get_id() << "\" />" << std::endl;
162  #endif
163 
164  this->DoWork(CurrentThreadStorage);
166  this->GetPerformanceLog().Insert( Whole(End-Begin)); // A whole is usually a 32 bit type, which is fine unless a single workunit runs for 35 minutes.
168 
169  #ifdef MEZZ_DEBUG
170  Out << "<WorkUnitEnd EndTimeStamp=\"" << End << "\" Duration=\"" << (End-Begin) << "\" DurationStored=\"" << Whole(End-Begin) << "\" />" << std::endl;
171  #endif
172  Out << "</WorkUnit>" << std::endl;
173  }
174 
176  { return WorkUnitKey( this->GetDependentCount(SchedulerToCount), GetPerformanceLog().GetAverage(), this); }
177 
178  }//Threading
179 }//Mezzanine
180 
181 #endif
virtual void AddDependency(iWorkUnit *NewDependency)
Force this WorkUnit to Start after another has completed.
Definition: workunit.cpp:99
virtual RunningState TakeOwnerShip()
Attempts to atomically start the work unit in the current thread.
Definition: workunit.cpp:125
virtual Whole GetDependentCountOf(iWorkUnit *Work, bool UsedCachedDepedentGraph=false)
How many other WorkUnit instances must wait on this one.
ThreadId MEZZ_LIB get_id()
Return the thread ID of the calling thread.
Stores data about a single work unit so that it can easily be sorted.
Definition: workunitkey.h:56
Int32 CurrentRunningState
This controls do work with this after it has.
Definition: workunit.h:172
RunningState
Used to track whether a thread has started, completed, etc...
std::vector< iWorkUnit * > Dependencies
A collection of of workunits that must be complete before this one can start.
Definition: workunit.h:169
MaxInt GetTimeStamp()
Get a timestamp, in microseconds. This will generally be some multiple of the GetTimeStampResolution ...
virtual Whole GetImmediateDependencyCount() const
Get the amount of dependencies that directly count on this for access purposes.
Definition: workunit.cpp:87
virtual bool IsEveryDependencyComplete()
Check if this WorkUnit could concievably run right now.
Definition: workunit.cpp:113
Interface of a WorkUnit. This represents on piece of work through time.
Definition: workunit.h:66
This file defines the template double buffered resources that can be attached to a thread...
virtual void operator()(DefaultThreadSpecificStorage::Type &CurrentThreadStorage)
This does everything required to track metadata and log work.
Definition: workunit.cpp:154
virtual void PrepareForNextFrame()
This resets the running state and takes any further action required to use the WorkUnit again...
Definition: workunit.cpp:139
virtual Whole GetDependencyCount() const
How many other WorkUnits does this one depend on?
Definition: workunit.cpp:90
Only used when a thread successfully attempts to gain ownership of a task, or some other tasks succes...
A thread specific collection of double-buffered and algorithm specific resources. ...
Int32 AtomicCompareAndSwap32(Int32 *VariableToChange, const Int32 &OldValue, const Int32 &NewValue)
Atomically Compares And Swaps a 32 bit value.
virtual Whole GetDependentCount(FrameScheduler &SchedulerToCount)
This returns the count workunits that depend on this work unit.
Definition: workunit.cpp:78
Task is running when the value was check, it could become Complete or Failed with no notice...
virtual iWorkUnit * GetDependency(Whole Index) const
This is used to iterate of all the dependencies.
Definition: workunit.cpp:84
This is central object in this algorithm, it is responsible for spawning threads and managing the ord...
virtual ~DefaultWorkUnit()
Virtual destructor, doesn't actually do much.
Definition: workunit.cpp:72
virtual RollingAverage< Whole > & GetPerformanceLog()
Get the internal rolling average for querying.
Definition: workunit.cpp:148
Logger & GetUsableLogger()
Get the usable logger for this thread specific resource.
The interface for rolling averages used in the Mezzanine, and threading library.
virtual void ClearDependencies()
Drop any information about what work units this one depends on.
Definition: workunit.cpp:110
virtual void DoWork(DefaultThreadSpecificStorage::Type &CurrentThreadStorage)=0
WorkUnits Must implement these to do the work.
Task is not yet started this frame, this can change without notice.
This file defines a minimalistic cross-platform thread that the scheduler uses to schedule tasks...
Simple thread safe ways to check and change a specified variable atomically.
long long MaxInt
A large integer type suitable for compile time math and long term microsecond time keeping...
Definition: datatypes.h:190
Thread has completed all work this from frame, will not change until this frame ends.
The bulk of the engine components go in this namspace.
Definition: actor.cpp:56
unsigned long Whole
Whole is an unsigned integer, it will be at least 32bits in size.
Definition: datatypes.h:151
virtual WorkUnitKey GetSortingKey(FrameScheduler &SchedulerToCount)
Get the sorting metadata.
Definition: workunit.cpp:175
virtual void RemoveDependency(iWorkUnit *RemoveDependency)
Remove a dependency.
Definition: workunit.cpp:102
virtual Whole GetPerformance() const
Get the internal rolling average for querying.
Definition: workunit.cpp:145
DefaultRollingAverage< Whole >::Type PerformanceLog
A rolling average of execution times.
Definition: workunit.h:166
DefaultWorkUnit()
Simple constructor.
Definition: workunit.cpp:69
virtual RunningState GetRunningState() const
Retrieves the current RunningState of the thread.
Definition: workunit.cpp:136
This file has the definition of the workunit.