1 // Copyright 2021 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CC_METRICS_SHARED_METRICS_BUFFER_H_
6 #define CC_METRICS_SHARED_METRICS_BUFFER_H_
8 #include "device/base/synchronization/one_writer_seqlock.h"
11 // The struct written in shared memory to transport metrics across
12 // processes. |data| is protected by the sequence-lock |seq_lock|.
13 // Note: This template copies data between processes. Any class that uses this
14 // template would need security review.
16 struct SharedMetricsBuffer {
17 device::OneWriterSeqLock seq_lock;
19 static_assert(std::is_trivially_copyable<T>::value,
20 "Metrics shared across processes need to be trivially "
21 "copyable, otherwise it is dangerous to copy it.");
23 bool Read(T& out) const {
24 const uint32_t kMaxRetries = 5;
26 base::subtle::Atomic32 version;
28 const uint32_t kMaxReadAttempts = 32;
29 version = seq_lock.ReadBegin(kMaxReadAttempts);
30 device::OneWriterSeqLock::AtomicReaderMemcpy(&out, &data, sizeof(T));
31 } while (seq_lock.ReadRetry(version) && ++retries < kMaxRetries);
33 // Consider the number of retries less than kMaxRetries as success.
34 return retries < kMaxRetries;
37 void Write(const T& in) {
38 seq_lock.WriteBegin();
39 device::OneWriterSeqLock::AtomicWriterMemcpy(&data, &in, sizeof(T));
46 #endif // CC_METRICS_SHARED_METRICS_BUFFER_H_