1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef BASE_TRACKED_OBJECTS_H_
6 #define BASE_TRACKED_OBJECTS_H_
16 #include "base/base_export.h"
17 #include "base/gtest_prod_util.h"
18 #include "base/lazy_instance.h"
19 #include "base/location.h"
20 #include "base/profiler/alternate_timer.h"
21 #include "base/profiler/tracked_time.h"
22 #include "base/time.h"
23 #include "base/synchronization/lock.h"
24 #include "base/threading/thread_local_storage.h"
25 #include "base/tracking_info.h"
26 #include "base/values.h"
28 // TrackedObjects provides a database of stats about objects (generally Tasks)
29 // that are tracked. Tracking means their birth, death, duration, birth thread,
30 // death thread, and birth place are recorded. This data is carefully spread
31 // across a series of objects so that the counts and times can be rapidly
32 // updated without (usually) having to lock the data, and hence there is usually
33 // very little contention caused by the tracking. The data can be viewed via
34 // the about:profiler URL, with a variety of sorting and filtering choices.
36 // These classes serve as the basis of a profiler of sorts for the Tasks system.
37 // As a result, design decisions were made to maximize speed, by minimizing
38 // recurring allocation/deallocation, lock contention and data copying. In the
39 // "stable" state, which is reached relatively quickly, there is no separate
40 // marginal allocation cost associated with construction or destruction of
41 // tracked objects, no locks are generally employed, and probably the largest
42 // computational cost is associated with obtaining start and stop times for
43 // instances as they are created and destroyed.
45 // The following describes the lifecycle of tracking an instance.
47 // First off, when the instance is created, the FROM_HERE macro is expanded
48 // to specify the birth place (file, line, function) where the instance was
49 // created. That data is used to create a transient Location instance
50 // encapsulating the above triple of information. The strings (like __FILE__)
51 // are passed around by reference, with the assumption that they are static, and
52 // will never go away. This ensures that the strings can be dealt with as atoms
53 // with great efficiency (i.e., copying of strings is never needed, and
54 // comparisons for equality can be based on pointer comparisons).
56 // Next, a Births instance is created for use ONLY on the thread where this
57 // instance was created. That Births instance records (in a base class
58 // BirthOnThread) references to the static data provided in a Location instance,
59 // as well as a pointer specifying the thread on which the birth takes place.
60 // Hence there is at most one Births instance for each Location on each thread.
61 // The derived Births class contains slots for recording statistics about all
62 // instances born at the same location. Statistics currently include only the
63 // count of instances constructed.
65 // Since the base class BirthOnThread contains only constant data, it can be
66 // freely accessed by any thread at any time (i.e., only the statistic needs to
67 // be handled carefully, and stats are updated exclusively on the birth thread).
69 // For Tasks, having now either constructed or found the Births instance
70 // described above, a pointer to the Births instance is then recorded into the
71 // PendingTask structure in MessageLoop. This fact alone is very useful in
72 // debugging, when there is a question of where an instance came from. In
73 // addition, the birth time is also recorded and used to later evaluate the
74 // lifetime duration of the whole Task. As a result of the above embedding, we
75 // can find out a Task's location of birth, and thread of birth, without using
76 // any locks, as all that data is constant across the life of the process.
78 // The above work *could* also be done for any other object as well by calling
79 // TallyABirthIfActive() and TallyRunOnNamedThreadIfTracking() as appropriate.
81 // The amount of memory used in the above data structures depends on how many
82 // threads there are, and how many Locations of construction there are.
83 // Fortunately, we don't use memory that is the product of those two counts, but
84 // rather we only need one Births instance for each thread that constructs an
85 // instance at a Location. In many cases, instances are only created on one
86 // thread, so the memory utilization is actually fairly restrained.
88 // Lastly, when an instance is deleted, the final tallies of statistics are
89 // carefully accumulated. That tallying writes into slots (members) in a
90 // collection of DeathData instances. For each birth place Location that is
91 // destroyed on a thread, there is a DeathData instance to record the additional
92 // death count, as well as accumulate the run-time and queue-time durations for
93 // the instance as it is destroyed (dies). By maintaining a single place to
94 // aggregate this running sum *only* for the given thread, we avoid the need to
95 // lock such DeathData instances. (i.e., these accumulated stats in a DeathData
96 // instance are exclusively updated by the singular owning thread).
98 // With the above lifecycle description complete, the major remaining detail is
99 // explaining how each thread maintains a list of DeathData instances, and of
100 // Births instances, and is able to avoid additional (redundant/unnecessary)
103 // Each thread maintains a list of data items specific to that thread in a
104 // ThreadData instance (for that specific thread only). The two critical items
105 // are lists of DeathData and Births instances. These lists are maintained in
106 // STL maps, which are indexed by Location. As noted earlier, we can compare
107 // locations very efficiently as we consider the underlying data (file,
108 // function, line) to be atoms, and hence pointer comparison is used rather than
109 // (slow) string comparisons.
111 // To provide a mechanism for iterating over all "known threads," which means
112 // threads that have recorded a birth or a death, we create a singly linked list
113 // of ThreadData instances. Each such instance maintains a pointer to the next
114 // one. A static member of ThreadData provides a pointer to the first item on
115 // this global list, and access via that all_thread_data_list_head_ item
116 // requires the use of the list_lock_.
117 // When new ThreadData instances is added to the global list, it is pre-pended,
118 // which ensures that any prior acquisition of the list is valid (i.e., the
119 // holder can iterate over it without fear of it changing, or the necessity of
120 // using an additional lock. Iterations are actually pretty rare (used
121 // primarilly for cleanup, or snapshotting data for display), so this lock has
122 // very little global performance impact.
124 // The above description tries to define the high performance (run time)
125 // portions of these classes. After gathering statistics, calls instigated
126 // by visiting about:profiler will assemble and aggregate data for display. The
127 // following data structures are used for producing such displays. They are
128 // not performance critical, and their only major constraint is that they should
129 // be able to run concurrently with ongoing augmentation of the birth and death
132 // For a given birth location, information about births is spread across data
133 // structures that are asynchronously changing on various threads. For display
134 // purposes, we need to construct Snapshot instances for each combination of
135 // birth thread, death thread, and location, along with the count of such
136 // lifetimes. We gather such data into a Snapshot instances, so that such
137 // instances can be sorted and aggregated (and remain frozen during our
138 // processing). Snapshot instances use pointers to constant portions of the
139 // birth and death datastructures, but have local (frozen) copies of the actual
140 // statistics (birth count, durations, etc. etc.).
142 // A DataCollector is a container object that holds a set of Snapshots. The
143 // statistics in a snapshot are gathered asynhcronously relative to their
144 // ongoing updates. It is possible, though highly unlikely, that stats could be
145 // incorrectly recorded by this process (all data is held in 32 bit ints, but we
146 // are not atomically collecting all data, so we could have count that does not,
147 // for example, match with the number of durations we accumulated). The
148 // advantage to having fast (non-atomic) updates of the data outweighs the
149 // minimal risk of a singular corrupt statistic snapshot (only the snapshot
150 // could be corrupt, not the underlying and ongoing statistic). In constrast,
151 // pointer data that is accessed during snapshotting is completely invariant,
152 // and hence is perfectly acquired (i.e., no potential corruption, and no risk
153 // of a bad memory reference).
155 // After an array of Snapshots instances are collected into a DataCollector,
156 // they need to be prepared for displaying our output. We currently implement a
157 // serialization into a Value hierarchy, which is automatically translated to
158 // JSON when supplied to rendering Java Scirpt.
160 // TODO(jar): We can implement a Snapshot system that *tries* to grab the
161 // snapshots on the source threads *when* they have MessageLoops available
162 // (worker threads don't have message loops generally, and hence gathering from
163 // them will continue to be asynchronous). We had an implementation of this in
164 // the past, but the difficulty is dealing with message loops being terminated.
165 // We can *try* to spam the available threads via some message loop proxy to
166 // achieve this feat, and it *might* be valuable when we are colecting data for
167 // upload via UMA (where correctness of data may be more significant than for a
168 // single screen of about:profiler).
170 // TODO(jar): We should support (optionally) the recording of parent-child
171 // relationships for tasks. This should be done by detecting what tasks are
172 // Born during the running of a parent task. The resulting data can be used by
173 // a smarter profiler to aggregate the cost of a series of child tasks into
174 // the ancestor task. It can also be used to illuminate what child or parent is
175 // related to each task.
177 // TODO(jar): We need to store DataCollections, and provide facilities for
178 // taking the difference between two gathered DataCollections. For now, we're
179 // just adding a hack that Reset()s to zero all counts and stats. This is also
180 // done in a slighly thread-unsafe fashion, as the resetting is done
181 // asynchronously relative to ongoing updates (but all data is 32 bit in size).
182 // For basic profiling, this will work "most of the time," and should be
183 // sufficient... but storing away DataCollections is the "right way" to do this.
184 // We'll accomplish this via JavaScript storage of snapshots, and then we'll
185 // remove the Reset() methods. We may also need a short-term-max value in
186 // DeathData that is reset (as synchronously as possible) during each snapshot.
187 // This will facilitate displaying a max value for each snapshot period.
189 namespace tracked_objects
{
191 //------------------------------------------------------------------------------
192 // For a specific thread, and a specific birth place, the collection of all
193 // death info (with tallies for each death thread, to prevent access conflicts).
195 class BASE_EXPORT BirthOnThread
{
197 BirthOnThread(const Location
& location
, const ThreadData
& current
);
199 const Location
location() const;
200 const ThreadData
* birth_thread() const;
202 // Insert our state (location, and thread name) into the dictionary.
203 // Use the supplied |prefix| in front of "thread_name" and "location"
204 // respectively when defining keys.
205 void ToValue(const std::string
& prefix
,
206 base::DictionaryValue
* dictionary
) const;
209 // File/lineno of birth. This defines the essence of the task, as the context
210 // of the birth (construction) often tell what the item is for. This field
211 // is const, and hence safe to access from any thread.
212 const Location location_
;
214 // The thread that records births into this object. Only this thread is
215 // allowed to update birth_count_ (which changes over time).
216 const ThreadData
* const birth_thread_
;
218 DISALLOW_COPY_AND_ASSIGN(BirthOnThread
);
221 //------------------------------------------------------------------------------
222 // A class for accumulating counts of births (without bothering with a map<>).
224 class BASE_EXPORT Births
: public BirthOnThread
{
226 Births(const Location
& location
, const ThreadData
& current
);
228 int birth_count() const;
230 // When we have a birth we update the count for this BirhPLace.
233 // When a birthplace is changed (updated), we need to decrement the counter
234 // for the old instance.
237 // Hack to quickly reset all counts to zero.
241 // The number of births on this thread for our location_.
244 DISALLOW_COPY_AND_ASSIGN(Births
);
247 //------------------------------------------------------------------------------
248 // Basic info summarizing multiple destructions of a tracked object with a
249 // single birthplace (fixed Location). Used both on specific threads, and also
250 // in snapshots when integrating assembled data.
252 class BASE_EXPORT DeathData
{
254 // Default initializer.
257 // When deaths have not yet taken place, and we gather data from all the
258 // threads, we create DeathData stats that tally the number of births without
259 // a corresponding death.
260 explicit DeathData(int count
);
262 // Update stats for a task destruction (death) that had a Run() time of
263 // |duration|, and has had a queueing delay of |queue_duration|.
264 void RecordDeath(const int32 queue_duration
,
265 const int32 run_duration
,
268 // Metrics accessors, used only in tests.
270 int32
run_duration_sum() const;
271 int32
run_duration_max() const;
272 int32
run_duration_sample() const;
273 int32
queue_duration_sum() const;
274 int32
queue_duration_max() const;
275 int32
queue_duration_sample() const;
277 // Construct a DictionaryValue instance containing all our stats. The caller
278 // assumes ownership of the returned instance.
279 base::DictionaryValue
* ToValue() const;
281 // Reset the max values to zero.
284 // Reset all tallies to zero. This is used as a hack on realtime data.
288 // Members are ordered from most regularly read and updated, to least
289 // frequently used. This might help a bit with cache lines.
290 // Number of runs seen (divisor for calculating averages).
292 // Basic tallies, used to compute averages.
293 int32 run_duration_sum_
;
294 int32 queue_duration_sum_
;
295 // Max values, used by local visualization routines. These are often read,
296 // but rarely updated.
297 int32 run_duration_max_
;
298 int32 queue_duration_max_
;
299 // Samples, used by by crowd sourcing gatherers. These are almost never read,
300 // and rarely updated.
301 int32 run_duration_sample_
;
302 int32 queue_duration_sample_
;
305 //------------------------------------------------------------------------------
306 // A temporary collection of data that can be sorted and summarized. It is
307 // gathered (carefully) from many threads. Instances are held in arrays and
308 // processed, filtered, and rendered.
309 // The source of this data was collected on many threads, and is asynchronously
310 // changing. The data in this instance is not asynchronously changing.
312 class BASE_EXPORT Snapshot
{
314 // When snapshotting a full life cycle set (birth-to-death), use this:
315 Snapshot(const BirthOnThread
& birth_on_thread
,
316 const ThreadData
& death_thread
,
317 const DeathData
& death_data
);
319 // When snapshotting a birth, with no death yet, use this:
320 Snapshot(const BirthOnThread
& birth_on_thread
, int count
);
322 // Accessor, that provides default value when there is no death thread.
323 const std::string
DeathThreadName() const;
325 // Construct a DictionaryValue instance containing all our data recursively.
326 // The caller assumes ownership of the memory in the returned instance.
327 base::DictionaryValue
* ToValue() const;
330 const BirthOnThread
* birth_
; // Includes Location and birth_thread.
331 const ThreadData
* death_thread_
;
332 DeathData death_data_
;
335 //------------------------------------------------------------------------------
336 // For each thread, we have a ThreadData that stores all tracking info generated
337 // on this thread. This prevents the need for locking as data accumulates.
338 // We use ThreadLocalStorage to quickly identfy the current ThreadData context.
339 // We also have a linked list of ThreadData instances, and that list is used to
340 // harvest data from all existing instances.
342 class BASE_EXPORT ThreadData
{
344 // Current allowable states of the tracking system. The states can vary
345 // between ACTIVE and DEACTIVATED, but can never go back to UNINITIALIZED.
347 UNINITIALIZED
, // PRistine, link-time state before running.
348 DORMANT_DURING_TESTS
, // Only used during testing.
349 DEACTIVATED
, // No longer recording profling.
350 PROFILING_ACTIVE
, // Recording profiles (no parent-child links).
351 PROFILING_CHILDREN_ACTIVE
, // Fully active, recording parent-child links.
354 typedef std::map
<Location
, Births
*> BirthMap
;
355 typedef std::map
<const Births
*, DeathData
> DeathMap
;
356 typedef std::pair
<const Births
*, const Births
*> ParentChildPair
;
357 typedef std::set
<ParentChildPair
> ParentChildSet
;
358 typedef std::stack
<const Births
*> ParentStack
;
360 // Initialize the current thread context with a new instance of ThreadData.
361 // This is used by all threads that have names, and should be explicitly
362 // set *before* any births on the threads have taken place. It is generally
363 // only used by the message loop, which has a well defined thread name.
364 static void InitializeThreadContext(const std::string
& suggested_name
);
366 // Using Thread Local Store, find the current instance for collecting data.
367 // If an instance does not exist, construct one (and remember it for use on
369 // This may return NULL if the system is disabled for any reason.
370 static ThreadData
* Get();
372 // Constructs a DictionaryValue instance containing all recursive results in
373 // our process. The caller assumes ownership of the memory in the returned
374 // instance. During the scavenging, if |reset_max| is true, then the
375 // DeathData instances max-values are reset to zero during this scan.
376 static base::DictionaryValue
* ToValue(bool reset_max
);
378 // Finds (or creates) a place to count births from the given location in this
379 // thread, and increment that tally.
380 // TallyABirthIfActive will returns NULL if the birth cannot be tallied.
381 static Births
* TallyABirthIfActive(const Location
& location
);
383 // Records the end of a timed run of an object. The |completed_task| contains
384 // a pointer to a Births, the time_posted, and a delayed_start_time if any.
385 // The |start_of_run| indicates when we started to perform the run of the
386 // task. The delayed_start_time is non-null for tasks that were posted as
387 // delayed tasks, and it indicates when the task should have run (i.e., when
388 // it should have posted out of the timer queue, and into the work queue.
389 // The |end_of_run| was just obtained by a call to Now() (just after the task
390 // finished). It is provided as an argument to help with testing.
391 static void TallyRunOnNamedThreadIfTracking(
392 const base::TrackingInfo
& completed_task
,
393 const TrackedTime
& start_of_run
,
394 const TrackedTime
& end_of_run
);
396 // Record the end of a timed run of an object. The |birth| is the record for
397 // the instance, the |time_posted| records that instant, which is presumed to
398 // be when the task was posted into a queue to run on a worker thread.
399 // The |start_of_run| is when the worker thread started to perform the run of
401 // The |end_of_run| was just obtained by a call to Now() (just after the task
403 static void TallyRunOnWorkerThreadIfTracking(
405 const TrackedTime
& time_posted
,
406 const TrackedTime
& start_of_run
,
407 const TrackedTime
& end_of_run
);
409 // Record the end of execution in region, generally corresponding to a scope
411 static void TallyRunInAScopedRegionIfTracking(
413 const TrackedTime
& start_of_run
,
414 const TrackedTime
& end_of_run
);
416 const std::string
thread_name() const;
418 // Snapshot (under a lock) copies of the maps in each ThreadData instance. For
419 // each set of maps (BirthMap, DeathMap, and ParentChildSet) call the Append()
420 // method of the |target| DataCollector. If |reset_max| is true, then the max
421 // values in each DeathData instance should be reset during the scan.
422 static void SendAllMaps(bool reset_max
, class DataCollector
* target
);
424 // Hack: asynchronously clear all birth counts and death tallies data values
425 // in all ThreadData instances. The numerical (zeroing) part is done without
426 // use of a locks or atomics exchanges, and may (for int64 values) produce
427 // bogus counts VERY rarely.
428 static void ResetAllThreadData();
430 // Initializes all statics if needed (this initialization call should be made
431 // while we are single threaded). Returns false if unable to initialize.
432 static bool Initialize();
434 // Sets internal status_.
435 // If |status| is false, then status_ is set to DEACTIVATED.
436 // If |status| is true, then status_ is set to, PROFILING_ACTIVE, or
437 // PROFILING_CHILDREN_ACTIVE.
438 // If tracking is not compiled in, this function will return false.
439 // If parent-child tracking is not compiled in, then an attempt to set the
440 // status to PROFILING_CHILDREN_ACTIVE will only result in a status of
441 // PROFILING_ACTIVE (i.e., it can't be set to a higher level than what is
442 // compiled into the binary, and parent-child tracking at the
443 // PROFILING_CHILDREN_ACTIVE level might not be compiled in).
444 static bool InitializeAndSetTrackingStatus(Status status
);
446 static Status
status();
448 // Indicate if any sort of profiling is being done (i.e., we are more than
450 static bool TrackingStatus();
452 // For testing only, indicate if the status of parent-child tracking is turned
453 // on. This is currently a compiled option, atop TrackingStatus().
454 static bool TrackingParentChildStatus();
456 // Special versions of Now() for getting times at start and end of a tracked
457 // run. They are super fast when tracking is disabled, and have some internal
458 // side effects when we are tracking, so that we can deduce the amount of time
459 // accumulated outside of execution of tracked runs.
460 // The task that will be tracked is passed in as |parent| so that parent-child
461 // relationships can be (optionally) calculated.
462 static TrackedTime
NowForStartOfRun(const Births
* parent
);
463 static TrackedTime
NowForEndOfRun();
465 // Provide a time function that does nothing (runs fast) when we don't have
466 // the profiler enabled. It will generally be optimized away when it is
467 // ifdef'ed to be small enough (allowing the profiler to be "compiled out" of
469 static TrackedTime
Now();
471 // Use the function |now| to provide current times, instead of calling the
472 // TrackedTime::Now() function. Since this alternate function is being used,
473 // the other time arguments (used for calculating queueing delay) will be
475 static void SetAlternateTimeSource(NowFunction
* now
);
477 // This function can be called at process termination to validate that thread
478 // cleanup routines have been called for at least some number of named
480 static void EnsureCleanupWasCalled(int major_threads_shutdown_count
);
483 // Allow only tests to call ShutdownSingleThreadedCleanup. We NEVER call it
484 // in production code.
485 // TODO(jar): Make this a friend in DEBUG only, so that the optimizer has a
486 // better change of optimizing (inlining? etc.) private methods (knowing that
487 // there will be no need for an external entry point).
488 friend class TrackedObjectsTest
;
489 FRIEND_TEST_ALL_PREFIXES(TrackedObjectsTest
, MinimalStartupShutdown
);
490 FRIEND_TEST_ALL_PREFIXES(TrackedObjectsTest
, TinyStartupShutdown
);
491 FRIEND_TEST_ALL_PREFIXES(TrackedObjectsTest
, ParentChildTest
);
493 // Worker thread construction creates a name since there is none.
494 explicit ThreadData(int thread_number
);
496 // Message loop based construction should provide a name.
497 explicit ThreadData(const std::string
& suggested_name
);
501 // Push this instance to the head of all_thread_data_list_head_, linking it to
502 // the previous head. This is performed after each construction, and leaves
503 // the instance permanently on that list.
504 void PushToHeadOfList();
506 // (Thread safe) Get start of list of all ThreadData instances using the lock.
507 static ThreadData
* first();
509 // Iterate through the null terminated list of ThreadData instances.
510 ThreadData
* next() const;
513 // In this thread's data, record a new birth.
514 Births
* TallyABirth(const Location
& location
);
516 // Find a place to record a death on this thread.
517 void TallyADeath(const Births
& birth
, int32 queue_duration
, int32 duration
);
519 // Using our lock, make a copy of the specified maps. This call may be made
520 // on non-local threads, which necessitate the use of the lock to prevent
521 // the map(s) from being reallocaed while they are copied. If |reset_max| is
522 // true, then, just after we copy the DeathMap, we will set the max values to
523 // zero in the active DeathMap (not the snapshot).
524 void SnapshotMaps(bool reset_max
,
527 ParentChildSet
* parent_child_set
);
529 // Using our lock to protect the iteration, Clear all birth and death data.
532 // This method is called by the TLS system when a thread terminates.
533 // The argument may be NULL if this thread has never tracked a birth or death.
534 static void OnThreadTermination(void* thread_data
);
536 // This method should be called when a worker thread terminates, so that we
537 // can save all the thread data into a cache of reusable ThreadData instances.
538 void OnThreadTerminationCleanup();
540 // Cleans up data structures, and returns statics to near pristine (mostly
541 // uninitialized) state. If there is any chance that other threads are still
542 // using the data structures, then the |leak| argument should be passed in as
543 // true, and the data structures (birth maps, death maps, ThreadData
544 // insntances, etc.) will be leaked and not deleted. If you have joined all
545 // threads since the time that InitializeAndSetTrackingStatus() was called,
546 // then you can pass in a |leak| value of false, and this function will
547 // delete recursively all data structures, starting with the list of
548 // ThreadData instances.
549 static void ShutdownSingleThreadedCleanup(bool leak
);
551 // When non-null, this specifies an external function that supplies monotone
552 // increasing time functcion.
553 static NowFunction
* now_function_
;
555 // We use thread local store to identify which ThreadData to interact with.
556 static base::ThreadLocalStorage::StaticSlot tls_index_
;
558 // List of ThreadData instances for use with worker threads. When a worker
559 // thread is done (terminated), we push it onto this llist. When a new worker
560 // thread is created, we first try to re-use a ThreadData instance from the
561 // list, and if none are available, construct a new one.
562 // This is only accessed while list_lock_ is held.
563 static ThreadData
* first_retired_worker_
;
565 // Link to the most recently created instance (starts a null terminated list).
566 // The list is traversed by about:profiler when it needs to snapshot data.
567 // This is only accessed while list_lock_ is held.
568 static ThreadData
* all_thread_data_list_head_
;
570 // The next available worker thread number. This should only be accessed when
571 // the list_lock_ is held.
572 static int worker_thread_data_creation_count_
;
574 // The number of times TLS has called us back to cleanup a ThreadData
575 // instance. This is only accessed while list_lock_ is held.
576 static int cleanup_count_
;
578 // Incarnation sequence number, indicating how many times (during unittests)
579 // we've either transitioned out of UNINITIALIZED, or into that state. This
580 // value is only accessed while the list_lock_ is held.
581 static int incarnation_counter_
;
583 // Protection for access to all_thread_data_list_head_, and to
584 // unregistered_thread_data_pool_. This lock is leaked at shutdown.
585 // The lock is very infrequently used, so we can afford to just make a lazy
586 // instance and be safe.
587 static base::LazyInstance
<base::Lock
>::Leaky list_lock_
;
589 // We set status_ to SHUTDOWN when we shut down the tracking service.
590 static Status status_
;
592 // Link to next instance (null terminated list). Used to globally track all
593 // registered instances (corresponds to all registered threads where we keep
597 // Pointer to another ThreadData instance for a Worker-Thread that has been
598 // retired (its thread was terminated). This value is non-NULL only for a
599 // retired ThreadData associated with a Worker-Thread.
600 ThreadData
* next_retired_worker_
;
602 // The name of the thread that is being recorded. If this thread has no
603 // message_loop, then this is a worker thread, with a sequence number postfix.
604 std::string thread_name_
;
606 // Indicate if this is a worker thread, and the ThreadData contexts should be
607 // stored in the unregistered_thread_data_pool_ when not in use.
608 // Value is zero when it is not a worker thread. Value is a positive integer
609 // corresponding to the created thread name if it is a worker thread.
610 int worker_thread_number_
;
612 // A map used on each thread to keep track of Births on this thread.
613 // This map should only be accessed on the thread it was constructed on.
614 // When a snapshot is needed, this structure can be locked in place for the
615 // duration of the snapshotting activity.
618 // Similar to birth_map_, this records informations about death of tracked
619 // instances (i.e., when a tracked instance was destroyed on this thread).
620 // It is locked before changing, and hence other threads may access it by
621 // locking before reading it.
624 // A set of parents that created children tasks on this thread. Each pair
625 // corresponds to potentially non-local Births (location and thread), and a
626 // local Births (that took place on this thread).
627 ParentChildSet parent_child_set_
;
629 // Lock to protect *some* access to BirthMap and DeathMap. The maps are
630 // regularly read and written on this thread, but may only be read from other
631 // threads. To support this, we acquire this lock if we are writing from this
632 // thread, or reading from another thread. For reading from this thread we
633 // don't need a lock, as there is no potential for a conflict since the
634 // writing is only done from this thread.
635 mutable base::Lock map_lock_
;
637 // The stack of parents that are currently being profiled. This includes only
638 // tasks that have started a timer recently via NowForStartOfRun(), but not
639 // yet concluded with a NowForEndOfRun(). Usually this stack is one deep, but
640 // if a scoped region is profiled, or <sigh> a task runs a nested-message
641 // loop, then the stack can grow larger. Note that we don't try to deduct
642 // time in nested porfiles, as our current timer is based on wall-clock time,
643 // and not CPU time (and we're hopeful that nested timing won't be a
644 // significant additional cost).
645 ParentStack parent_stack_
;
647 // A random number that we used to select decide which sample to keep as a
648 // representative sample in each DeathData instance. We can't start off with
649 // much randomness (because we can't call RandInt() on all our threads), so
650 // we stir in more and more as we go.
651 int32 random_number_
;
653 // Record of what the incarnation_counter_ was when this instance was created.
654 // If the incarnation_counter_ has changed, then we avoid pushing into the
655 // pool (this is only critical in tests which go through multiple
657 int incarnation_count_for_pool_
;
659 DISALLOW_COPY_AND_ASSIGN(ThreadData
);
662 //------------------------------------------------------------------------------
663 // DataCollector is a container class for Snapshot and BirthOnThread count
666 class BASE_EXPORT DataCollector
{
668 typedef std::vector
<Snapshot
> Collection
;
670 // Construct with a list of how many threads should contribute. This helps us
671 // determine (in the async case) when we are done with all contributions.
675 // Adds all stats from the indicated thread into our arrays. Accepts copies
676 // of the birth_map and death_map, so that the data will not change during the
677 // iterations and processing.
678 void Append(const ThreadData
&thread_data
,
679 const ThreadData::BirthMap
& birth_map
,
680 const ThreadData::DeathMap
& death_map
,
681 const ThreadData::ParentChildSet
& parent_child_set
);
683 // After the accumulation phase, the following accessor is used to process the
684 // data (i.e., sort it, filter it, etc.).
685 Collection
* collection();
687 // Adds entries for all the remaining living objects (objects that have
688 // tallied a birth, but have not yet tallied a matching death, and hence must
689 // be either running, queued up, or being held in limbo for future posting).
690 // This should be called after all known ThreadData instances have been
691 // processed using Append().
692 void AddListOfLivingObjects();
694 // Generates a ListValue representation of the vector of snapshots, and
695 // inserts the results into |dictionary|.
696 void ToValue(base::DictionaryValue
* dictionary
) const;
699 typedef std::map
<const BirthOnThread
*, int> BirthCount
;
701 // The array that we collect data into.
702 Collection collection_
;
704 // The total number of births recorded at each location for which we have not
705 // seen a death count. This map changes as we do Append() calls, and is later
706 // used by AddListOfLivingObjects() to gather up unaccounted for births.
707 BirthCount global_birth_count_
;
709 // The complete list of parent-child relationships among tasks.
710 ThreadData::ParentChildSet parent_child_set_
;
712 DISALLOW_COPY_AND_ASSIGN(DataCollector
);
715 } // namespace tracked_objects
717 #endif // BASE_TRACKED_OBJECTS_H_