Chromium Code Reviews| Index: base/profiler/stack_sampling_profiler.cc |
| diff --git a/base/profiler/stack_sampling_profiler.cc b/base/profiler/stack_sampling_profiler.cc |
| index f294251cd32b6dff9d3b3b4bee1bbf8134e66ba7..7497c7639a45caf1c84a8f2019fdec3f4790a823 100644 |
| --- a/base/profiler/stack_sampling_profiler.cc |
| +++ b/base/profiler/stack_sampling_profiler.cc |
| @@ -5,16 +5,22 @@ |
| #include "base/profiler/stack_sampling_profiler.h" |
| #include <algorithm> |
| +#include <map> |
| #include <utility> |
| +#include "base/atomic_sequence_num.h" |
| +#include "base/atomicops.h" |
| #include "base/bind.h" |
| #include "base/bind_helpers.h" |
| #include "base/callback.h" |
| #include "base/lazy_instance.h" |
| #include "base/location.h" |
| #include "base/macros.h" |
| +#include "base/memory/ptr_util.h" |
| +#include "base/memory/singleton.h" |
| #include "base/profiler/native_stack_sampler.h" |
| #include "base/synchronization/lock.h" |
| +#include "base/threading/thread.h" |
| #include "base/threading/thread_task_runner_handle.h" |
| #include "base/timer/elapsed_timer.h" |
| @@ -22,9 +28,6 @@ namespace base { |
| namespace { |
| -// Used to ensure only one profiler is running at a time. |
| -LazyInstance<Lock>::Leaky concurrent_profiling_lock = LAZY_INSTANCE_INITIALIZER; |
| - |
| // AsyncRunner ---------------------------------------------------------------- |
| // Helper class to allow a profiler to be run completely asynchronously from the |
| @@ -160,102 +163,468 @@ StackSamplingProfiler::CallStackProfile::CallStackProfile( |
| // StackSamplingProfiler::SamplingThread -------------------------------------- |
| -StackSamplingProfiler::SamplingThread::SamplingThread( |
| - std::unique_ptr<NativeStackSampler> native_sampler, |
| - const SamplingParams& params, |
| - const CompletedCallback& completed_callback) |
| - : native_sampler_(std::move(native_sampler)), |
| - params_(params), |
| - stop_event_(WaitableEvent::ResetPolicy::AUTOMATIC, |
| - WaitableEvent::InitialState::NOT_SIGNALED), |
| - completed_callback_(completed_callback) {} |
| +class StackSamplingProfiler::SamplingThread : public Thread { |
| + public: |
| + struct CollectionContext { |
| + CollectionContext(PlatformThreadId target, |
| + const SamplingParams& params, |
| + const CompletedCallback& callback, |
| + std::unique_ptr<NativeStackSampler> sampler) |
| + : collection_id(next_collection_id_.GetNext()), |
| + target(target), |
| + params(params), |
| + callback(callback), |
| + native_sampler(std::move(sampler)) {} |
| + ~CollectionContext() {} |
| + |
| + // An identifier for this collection, used to uniquely identify it to |
| + // outside interests. |
| + const int collection_id; |
| + |
| + Time next_sample_time; |
| + |
| + PlatformThreadId target; |
| + SamplingParams params; |
| + CompletedCallback callback; |
| + |
| + std::unique_ptr<NativeStackSampler> native_sampler; |
| + |
| + // Counters that indicate the current position along the acquisition. |
| + int burst = 0; |
| + int sample = 0; |
| + |
| + // The time that a profile was started, for calculating the total duration. |
| + Time profile_start_time; |
| + |
| + // The collected stack samples. The active profile is always at the back(). |
| + CallStackProfiles profiles; |
| + |
| + private: |
| + static StaticAtomicSequenceNumber next_collection_id_; |
| + }; |
| + |
| + // Gets the single instance of this class. |
| + static SamplingThread* GetInstance(); |
| + |
| + // Starts the thread. |
| + void Start(); |
| + |
| + // Adds a new CollectionContext to the thread. This can be called externally |
| + // from any thread. This returns an ID that can later be used to stop |
| + // the sampling. |
| + int Add(std::unique_ptr<CollectionContext> collection); |
| -StackSamplingProfiler::SamplingThread::~SamplingThread() {} |
| + // Removes an active collection based on its ID, forcing it to run its |
| + // callback if any data has been collected. This can be called externally |
| + // from any thread. |
| + void Remove(int id); |
| -void StackSamplingProfiler::SamplingThread::ThreadMain() { |
| - PlatformThread::SetName("Chrome_SamplingProfilerThread"); |
| + // Removes all active collections and stops the underlying thread. |
| + void Shutdown(); |
| + |
| + // Begins an idle shutdown as if the idle-timer had expired. |
| + void ShutdownIfIdle(); |
| + |
| + // Undoes the "permanent" effect of Shutdown() so the thread can restart. |
| + void UndoShutdown(); |
| + |
| + // Sets the number of ms to wait after becoming idle before shutting down. |
| + // Set to zero to disable. |
| + void SetIdleShutdownTime(int shutdown_ms); |
| + |
| + private: |
| + SamplingThread(); |
| + ~SamplingThread() override; |
| + friend struct DefaultSingletonTraits<SamplingThread>; |
| + |
| + // Get task runner that is usable from the outside. |
| + scoped_refptr<SingleThreadTaskRunner> GetOrCreateTaskRunner(); |
| + scoped_refptr<SingleThreadTaskRunner> GetTaskRunner(); |
| + |
| + // Get task runner that is usable from the sampling thread itself. |
| + scoped_refptr<SingleThreadTaskRunner> GetTaskRunnerOnSamplingThread(); |
| + |
| + // Finishes a collection and reports collected data via callback. |
| + void FinishCollection(CollectionContext* collection); |
| + |
| + // Records a single sample of a collection. |
| + void RecordSample(CollectionContext* collection); |
| + |
| + // Check if the sampling thread is idle. |
| + void CheckForIdle(); |
| + |
| + // These methods are tasks that get posted to the internal message queue. |
| + void AddCollectionTask(std::unique_ptr<CollectionContext> collection_ptr); |
| + void RemoveCollectionTask(int id); |
| + void PerformCollectionTask(int id); |
| + void ShutdownTask(); |
| + |
| + // Updates the |next_sample_time| time based on configured parameters. |
| + bool UpdateNextSampleTime(CollectionContext* collection); |
| + |
| + // Thread: |
| + void CleanUp() override; |
| + |
| + // The task-runner for the sampling thread and some information about it. |
| + // This must always be accessed while holding the lock. The saved task-runner |
| + // can be freely used by any calling thread. |
| + scoped_refptr<SingleThreadTaskRunner> task_runner_; |
| + bool task_runner_forced_shutdown_ = false; |
| + int task_runner_create_requests_ = 0; |
| + TimeDelta task_runner_idle_shutdown_time_ = TimeDelta::FromSeconds(5); |
| + Lock task_runner_lock_; |
| + |
| + // A map of IDs to collection contexts. Because this class is a singleton |
| + // that is never destroyed, context objects will never be destructed except |
| + // by explicit action. Thus, it's acceptable to pass unretained pointers |
| + // to these objects when posting tasks. |
| + std::map<int, std::unique_ptr<CollectionContext>> active_collections_; |
| + |
| + DISALLOW_COPY_AND_ASSIGN(SamplingThread); |
| +}; |
| + |
| +StaticAtomicSequenceNumber StackSamplingProfiler::SamplingThread:: |
| + CollectionContext::next_collection_id_; |
| + |
| +StackSamplingProfiler::SamplingThread::SamplingThread() |
| + : Thread("Chrome_SamplingProfilerThread") {} |
| + |
| +StackSamplingProfiler::SamplingThread::~SamplingThread() { |
| + Thread::Stop(); |
| +} |
| + |
| +StackSamplingProfiler::SamplingThread* |
| +StackSamplingProfiler::SamplingThread::GetInstance() { |
| + return Singleton<SamplingThread, LeakySingletonTraits<SamplingThread>>::get(); |
| +} |
| + |
| +void StackSamplingProfiler::SamplingThread::Start() { |
| + Thread::Options options; |
| + // Use a higher priority for a more accurate sampling interval. |
| + options.priority = ThreadPriority::DISPLAY; |
| + Thread::StartWithOptions(options); |
| +} |
| - // For now, just ignore any requests to profile while another profiler is |
| - // working. |
| - if (!concurrent_profiling_lock.Get().Try()) |
| +int StackSamplingProfiler::SamplingThread::Add( |
| + std::unique_ptr<CollectionContext> collection) { |
| + int id = collection->collection_id; |
| + scoped_refptr<SingleThreadTaskRunner> task_runner = GetOrCreateTaskRunner(); |
| + |
| + // There may be no task-runner if the sampling thread has been permanently |
| + // shut down. |
| + if (task_runner) { |
| + task_runner->PostTask( |
| + FROM_HERE, Bind(&SamplingThread::AddCollectionTask, Unretained(this), |
| + Passed(&collection))); |
| + } |
| + return id; |
| +} |
| + |
| +void StackSamplingProfiler::SamplingThread::Remove(int id) { |
| + scoped_refptr<SingleThreadTaskRunner> task_runner = GetTaskRunner(); |
| + if (!task_runner) |
| + return; // Everything has already stopped. |
| + |
| + // This can fail if the thread were to exit between acquisition of the task |
| + // runner above and the call below. In that case, however, everything has |
| + // stopped so there's no need to try to stop it. |
| + task_runner->PostTask(FROM_HERE, Bind(&SamplingThread::RemoveCollectionTask, |
| + Unretained(this), id)); |
| +} |
| + |
| +void StackSamplingProfiler::SamplingThread::Shutdown() { |
| + // Record that a shutdown has been requested so nothing can cause it to |
| + // start up again. |
| + { |
| + AutoLock lock(task_runner_lock_); |
| + task_runner_forced_shutdown_ = true; |
| + } |
| + |
| + scoped_refptr<SingleThreadTaskRunner> task_runner = GetTaskRunner(); |
| + if (!task_runner) |
| + return; // Everything has already stopped. |
| + |
| + // This can fail if the thread were to exit between acquisition of the task |
| + // runner above and the call below. In that case, however, everything has |
| + // stopped so there's no need to do anything. |
| + task_runner->PostTask(FROM_HERE, |
| + Bind(&SamplingThread::ShutdownTask, Unretained(this))); |
| + |
| + // Now that a task has been posted, calling Stop() will block until that task |
| + // has been executed. |
| + Stop(); |
| +} |
| + |
| +void StackSamplingProfiler::SamplingThread::ShutdownIfIdle() { |
| + scoped_refptr<SingleThreadTaskRunner> task_runner = GetTaskRunner(); |
| + if (!task_runner) |
| + return; // Everything has already stopped. |
| + |
| + // ShutdownTask will check if the thread is idle and skip the shutdown if not. |
| + task_runner->PostTask(FROM_HERE, |
| + Bind(&SamplingThread::ShutdownTask, Unretained(this))); |
| +} |
| + |
| +void StackSamplingProfiler::SamplingThread::UndoShutdown() { |
| + { |
| + AutoLock lock(task_runner_lock_); |
| + task_runner_forced_shutdown_ = false; |
| + } |
| +} |
| + |
| +void StackSamplingProfiler::SamplingThread::SetIdleShutdownTime( |
| + int shutdown_ms) { |
| + AutoLock lock(task_runner_lock_); |
| + task_runner_idle_shutdown_time_ = TimeDelta::FromMilliseconds(shutdown_ms); |
| +} |
| + |
| +scoped_refptr<SingleThreadTaskRunner> |
| +StackSamplingProfiler::SamplingThread::GetOrCreateTaskRunner() { |
| + AutoLock lock(task_runner_lock_); |
| + ++task_runner_create_requests_; |
| + if (!task_runner_) { |
| + // If a forced shutdown has been done, don't let it restart. |
| + if (task_runner_forced_shutdown_) |
| + return nullptr; |
| + // If this is not the first time the sampling thread has been launched, the |
| + // previous instance has only been partially cleaned up. It is necessary |
| + // to call Stop() before Start(). This is safe even the thread has never |
| + // been started. |
| + Stop(); |
| + // The thread is not running. Start it and get associated runner. The task- |
| + // runner has to be saved for future use because though it can be used from |
| + // any thread, it can be acquired via task_runner() only on the created |
| + // thread and the thread that creates it (i.e. this thread). |
| + Start(); |
| + task_runner_ = Thread::task_runner(); |
| + // Detach the sampling thread from the "sequence" (i.e. thread) that |
| + // started it so that it can be self-managed or stopped on by another |
| + // thread. |
| + DetachFromSequence(); |
| + } else { |
| + // This shouldn't be called from the sampling thread as it's inefficient. |
| + // Use GetTaskRunnerOnSamplingThread() instead. |
| + DCHECK_NE(GetThreadId(), PlatformThread::CurrentId()); |
| + } |
| + |
| + return task_runner_; |
| +} |
| + |
| +scoped_refptr<SingleThreadTaskRunner> |
| +StackSamplingProfiler::SamplingThread::GetTaskRunner() { |
| + // This shouldn't be called from the sampling thread as it's inefficient. Use |
| + // GetTaskRunnerOnSamplingThread() instead. |
| + DCHECK_NE(GetThreadId(), PlatformThread::CurrentId()); |
| + |
| + AutoLock lock(task_runner_lock_); |
| + return task_runner_; |
| +} |
| + |
| +scoped_refptr<SingleThreadTaskRunner> |
| +StackSamplingProfiler::SamplingThread::GetTaskRunnerOnSamplingThread() { |
| + // This should be called only from the sampling thread as it has limited |
| + // accessibility. |
| + DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); |
| + |
| + return Thread::task_runner(); |
| +} |
| + |
| +void StackSamplingProfiler::SamplingThread::FinishCollection( |
| + CollectionContext* collection) { |
| + // If there is no duration for the final profile (because it was stopped), |
| + // calculated it now. |
| + if (!collection->profiles.empty() && |
| + collection->profiles.back().profile_duration == TimeDelta()) { |
| + collection->profiles.back().profile_duration = |
| + Time::Now() - collection->profile_start_time; |
| + } |
| + |
| + // Run the associated callback, passing the collected profiles. It's okay to |
| + // move them because this collection is about to be deleted. |
| + collection->callback.Run(std::move(collection->profiles)); |
| + |
| + // Remove this collection from the map of known ones. This must be done |
| + // last as the |collection| parameter is invalid after this point. |
| + size_t count = active_collections_.erase(collection->collection_id); |
| + DCHECK_EQ(1U, count); |
| +} |
| + |
| +void StackSamplingProfiler::SamplingThread::RecordSample( |
| + CollectionContext* collection) { |
| + DCHECK(collection->native_sampler); |
| + |
| + // If this is the first sample of a burst, a new Profile needs to be created |
| + // and filled. |
| + if (collection->sample == 0) { |
| + collection->profiles.push_back(CallStackProfile()); |
| + CallStackProfile& profile = collection->profiles.back(); |
| + profile.sampling_period = collection->params.sampling_interval; |
| + collection->profile_start_time = Time::Now(); |
| + collection->native_sampler->ProfileRecordingStarting(&profile.modules); |
| + } |
| + |
| + // The currently active profile being acptured. |
| + CallStackProfile& profile = collection->profiles.back(); |
| + |
| + // Record a single sample. |
| + profile.samples.push_back(Sample()); |
| + Sample& sample = profile.samples.back(); |
| + collection->native_sampler->RecordStackSample(&sample); |
| + |
| + // An empty result indicates that the thread under test is gone. |
|
Mike Wittman
2017/01/31 22:14:27
I don't think relying on SuspendThread to error ou
bcwhite
2017/02/01 14:47:29
While reuse of thread-ids is possible, I don't thi
Mike Wittman
2017/02/01 17:59:53
I think this is a serious concern, and requires a
bcwhite
2017/02/01 19:11:16
I don't understand. The StackSamplingProfiler lif
Mike Wittman
2017/02/01 20:26:51
That's true, the current interface allows an arbit
bcwhite
2017/02/01 20:37:59
If the call were made while the thread was suspend
Mike Wittman
2017/02/01 21:19:04
There would still be a race between the time the t
bcwhite
2017/02/01 22:01:47
The thread creation time would be captured during
Mike Wittman
2017/02/02 02:48:05
I am not convinced that we've enumerated and addre
bcwhite
2017/02/02 14:24:25
Undocumented? GetThreadTimes is a published and s
Mike Wittman
2017/02/02 19:22:31
Several points:
1. Running the check after the sa
bcwhite
2017/02/02 20:46:16
100ms? If the check happens immediately after the
Mike Wittman
2017/02/02 22:29:15
Are you presuming the GetThreadTimes call is made
bcwhite
2017/02/03 13:28:38
Okay, you've convinced me: If a thread were to exi
Mike Wittman
2017/02/03 17:24:15
No, sorry, I don't agree.
Support for other OS's
bcwhite
2017/02/03 18:47:58
Correct. Or at least to a different CL.
Mike Wittman
2017/02/04 01:09:29
The complexity is inherent in this change: it adds
bcwhite
2017/02/04 02:07:01
Not true. I can remove completely everything I ad
Mike Wittman
2017/02/06 20:54:06
Even if the interface is updated to be the same ac
|
| + if (sample.frames.empty()) { |
| + // Indicate that collection is complete so it stops below and finishes. |
| + // The empty frame remains as an indicator during analysis that the |
| + // thread exited. |
| + collection->sample = collection->params.samples_per_burst - 1; |
| + collection->burst = collection->params.bursts - 1; |
| + } |
| + |
| + // If this is the last sample of a burst, record the total time. |
| + if (collection->sample == collection->params.samples_per_burst - 1) { |
| + profile.profile_duration = Time::Now() - collection->profile_start_time; |
| + collection->native_sampler->ProfileRecordingStopped(); |
| + } |
| +} |
| + |
| +void StackSamplingProfiler::SamplingThread::CheckForIdle() { |
| + if (!active_collections_.empty()) |
| return; |
| - CallStackProfiles profiles; |
| - CollectProfiles(&profiles); |
| - concurrent_profiling_lock.Get().Release(); |
| - completed_callback_.Run(std::move(profiles)); |
| -} |
| - |
| -// Depending on how long the sampling takes and the length of the sampling |
| -// interval, a burst of samples could take arbitrarily longer than |
| -// samples_per_burst * sampling_interval. In this case, we (somewhat |
| -// arbitrarily) honor the number of samples requested rather than strictly |
| -// adhering to the sampling intervals. Once we have established users for the |
| -// StackSamplingProfiler and the collected data to judge, we may go the other |
| -// way or make this behavior configurable. |
| -void StackSamplingProfiler::SamplingThread::CollectProfile( |
| - CallStackProfile* profile, |
| - TimeDelta* elapsed_time, |
| - bool* was_stopped) { |
| - ElapsedTimer profile_timer; |
| - native_sampler_->ProfileRecordingStarting(&profile->modules); |
| - profile->sampling_period = params_.sampling_interval; |
| - *was_stopped = false; |
| - TimeDelta previous_elapsed_sample_time; |
| - for (int i = 0; i < params_.samples_per_burst; ++i) { |
| - if (i != 0) { |
| - // Always wait, even if for 0 seconds, so we can observe a signal on |
| - // stop_event_. |
| - if (stop_event_.TimedWait( |
| - std::max(params_.sampling_interval - previous_elapsed_sample_time, |
| - TimeDelta()))) { |
| - *was_stopped = true; |
| - break; |
| - } |
| - } |
| - ElapsedTimer sample_timer; |
| - profile->samples.push_back(Sample()); |
| - native_sampler_->RecordStackSample(&profile->samples.back()); |
| - previous_elapsed_sample_time = sample_timer.Elapsed(); |
| + AutoLock lock(task_runner_lock_); |
| + if (!task_runner_idle_shutdown_time_.is_zero()) { |
| + GetTaskRunnerOnSamplingThread()->PostDelayedTask( |
| + FROM_HERE, Bind(&SamplingThread::ShutdownTask, Unretained(this)), |
| + task_runner_idle_shutdown_time_); |
| } |
| +} |
| - *elapsed_time = profile_timer.Elapsed(); |
| - profile->profile_duration = *elapsed_time; |
| - native_sampler_->ProfileRecordingStopped(); |
| +void StackSamplingProfiler::SamplingThread::AddCollectionTask( |
| + std::unique_ptr<CollectionContext> collection_ptr) { |
| + // Ownership of the collection is going to be given to a map but a pointer |
| + // to it will be needed later. |
| + CollectionContext* collection = collection_ptr.get(); |
| + active_collections_.insert( |
| + std::make_pair(collection->collection_id, std::move(collection_ptr))); |
| + |
| + GetTaskRunnerOnSamplingThread()->PostDelayedTask( |
| + FROM_HERE, Bind(&SamplingThread::PerformCollectionTask, Unretained(this), |
| + collection->collection_id), |
| + collection->params.initial_delay); |
| } |
| -// In an analogous manner to CollectProfile() and samples exceeding the expected |
| -// total sampling time, bursts may also exceed the burst_interval. We adopt the |
| -// same wait-and-see approach here. |
| -void StackSamplingProfiler::SamplingThread::CollectProfiles( |
| - CallStackProfiles* profiles) { |
| - if (stop_event_.TimedWait(params_.initial_delay)) |
| +void StackSamplingProfiler::SamplingThread::RemoveCollectionTask(int id) { |
| + auto found = active_collections_.find(id); |
| + if (found == active_collections_.end()) |
| return; |
| - TimeDelta previous_elapsed_profile_time; |
| - for (int i = 0; i < params_.bursts; ++i) { |
| - if (i != 0) { |
| - // Always wait, even if for 0 seconds, so we can observe a signal on |
| - // stop_event_. |
| - if (stop_event_.TimedWait( |
| - std::max(params_.burst_interval - previous_elapsed_profile_time, |
| - TimeDelta()))) |
| - return; |
| - } |
| + FinishCollection(found->second.get()); |
| + CheckForIdle(); |
| +} |
| - CallStackProfile profile; |
| - bool was_stopped = false; |
| - CollectProfile(&profile, &previous_elapsed_profile_time, &was_stopped); |
| - if (!profile.samples.empty()) |
| - profiles->push_back(std::move(profile)); |
| +void StackSamplingProfiler::SamplingThread::PerformCollectionTask(int id) { |
| + auto found = active_collections_.find(id); |
| - if (was_stopped) |
| + // The task won't be found if it has been stopped. |
| + if (found == active_collections_.end()) |
| + return; |
| + |
| + CollectionContext* collection = found->second.get(); |
| + |
| + // Handle first-run with no "next time". |
| + if (collection->next_sample_time == Time()) |
| + collection->next_sample_time = Time::Now(); |
| + |
| + // Do the collection of a single sample. |
| + RecordSample(collection); |
| + |
| + // Update the time of the next sample recording. |
| + if (UpdateNextSampleTime(collection)) { |
| + bool success = GetTaskRunnerOnSamplingThread()->PostDelayedTask( |
| + FROM_HERE, |
| + Bind(&SamplingThread::PerformCollectionTask, Unretained(this), id), |
| + std::max(collection->next_sample_time - Time::Now(), TimeDelta())); |
| + DCHECK(success); |
| + } else { |
| + // All capturing has completed so finish the collection. Let object expire. |
| + // The |collection| variable will be invalid after this call. |
| + FinishCollection(collection); |
| + CheckForIdle(); |
| + } |
| +} |
| + |
| +void StackSamplingProfiler::SamplingThread::ShutdownTask() { |
| + // Holding this lock ensures that any attempt to start another job will |
| + // get postponed until StopSoon can run thus eliminating the race. |
| + AutoLock lock(task_runner_lock_); |
| + |
| + // If this is a forced, permanent shutdown, stop all active collections. |
| + if (task_runner_forced_shutdown_) { |
| + // FinishCollection will remove the entry thus invalidating any iterator. |
| + while (!active_collections_.empty()) |
| + FinishCollection(active_collections_.begin()->second.get()); |
| + } else { |
| + // If active_collections_ is not empty, something new has arrived since |
| + // this task got posted. Abort the shutdown so it can be processed. |
| + if (!active_collections_.empty()) |
| + return; |
| + // It's possible that a new AddCollectionTask has been posted after this |
| + // task. Reset the "create requests" counter and try again after any other |
| + // pending tasks. |
| + if (task_runner_create_requests_ > 0 && task_runner_) { |
| + task_runner_create_requests_ = 0; |
| + task_runner_->PostTask( |
| + FROM_HERE, Bind(&SamplingThread::ShutdownTask, Unretained(this))); |
| return; |
| + } |
| + // There can be no new AddCollectionTasks at this point because creating |
| + // those always increments "create requests". There may be other requests, |
| + // like Remove, but it's okay to schedule the thread to stop once they've |
| + // been executed (i.e. "soon"). |
| } |
| + |
| + // Stop the underlying thread as soon as all immediate tasks are complete. |
| + // Calling Stop() directly would result in deadlock. |
| + StopSoon(); |
| + |
| + // StopSoon will have set the owning sequence (again) so it must be detached |
| + // (again) in order for Stop/Start to be called (again) should more work |
| + // come in. Holding the |task_runner_lock_| ensures the necessary happens- |
| + // after with regard to this detach and future Thread API calls. |
| + DetachFromSequence(); |
| + |
| + // Clear the task_runner_ variable so the thread will be restarted when |
| + // new work comes in. |
| + task_runner_ = nullptr; |
| +} |
| + |
| +bool StackSamplingProfiler::SamplingThread::UpdateNextSampleTime( |
| + CollectionContext* collection) { |
| + if (++collection->sample < collection->params.samples_per_burst) { |
| + collection->next_sample_time += collection->params.sampling_interval; |
| + return true; |
| + } |
| + |
| + // This will keep a consistent average interval between samples but will |
| + // result in constant series of acquisitions, thus nearly locking out the |
| + // target thread, if the interval is smaller than the time it takes to |
| + // actually acquire the sample. Anything sampling that quickly is going |
| + // to be a problem anyway so don't worry about it. |
| + if (++collection->burst < collection->params.bursts) { |
| + collection->sample = 0; |
| + collection->next_sample_time += collection->params.burst_interval; |
| + return true; |
| + } |
| + |
| + return false; |
| } |
| -void StackSamplingProfiler::SamplingThread::Stop() { |
| - stop_event_.Signal(); |
| +void StackSamplingProfiler::SamplingThread::CleanUp() { |
| + // There should be no collections remaining when the thread stops. |
| + DCHECK(active_collections_.empty()); |
| + |
| + // Let the parent clean up. |
| + Thread::CleanUp(); |
| } |
| // StackSamplingProfiler ------------------------------------------------------ |
| @@ -287,8 +656,6 @@ StackSamplingProfiler::StackSamplingProfiler( |
| StackSamplingProfiler::~StackSamplingProfiler() { |
| Stop(); |
| - if (!sampling_thread_handle_.is_null()) |
| - PlatformThread::Join(sampling_thread_handle_); |
| } |
| // static |
| @@ -310,16 +677,39 @@ void StackSamplingProfiler::Start() { |
| if (!native_sampler) |
| return; |
| - sampling_thread_.reset(new SamplingThread(std::move(native_sampler), params_, |
| - completed_callback_)); |
| - if (!PlatformThread::Create(0, sampling_thread_.get(), |
| - &sampling_thread_handle_)) |
| - sampling_thread_.reset(); |
| + collection_id_ = SamplingThread::GetInstance()->Add( |
| + MakeUnique<SamplingThread::CollectionContext>( |
| + thread_id_, params_, completed_callback_, std::move(native_sampler))); |
| } |
| void StackSamplingProfiler::Stop() { |
| - if (sampling_thread_) |
| - sampling_thread_->Stop(); |
| + SamplingThread::GetInstance()->Remove(collection_id_); |
| +} |
| + |
| +// static |
| +void StackSamplingProfiler::Shutdown() { |
| + SamplingThread::GetInstance()->Shutdown(); |
| +} |
| + |
| +// static |
| +void StackSamplingProfiler::UndoShutdownForTesting() { |
| + SamplingThread::GetInstance()->UndoShutdown(); |
| +} |
| + |
| +// static |
| +bool StackSamplingProfiler::IsSamplingThreadRunningForTesting() { |
| + return SamplingThread::GetInstance()->IsRunning(); |
| +} |
| + |
| +// static |
| +void StackSamplingProfiler::SetSamplingThreadIdleShutdownTimeForTesting( |
| + int shutdown_ms) { |
| + SamplingThread::GetInstance()->SetIdleShutdownTime(shutdown_ms); |
| +} |
| + |
| +// static |
| +void StackSamplingProfiler::InitiateSamplingThreadIdleShutdownForTesting() { |
| + SamplingThread::GetInstance()->ShutdownIfIdle(); |
| } |
| // static |