diff --git a/cameraserver/src/main/native/cpp/cameraserver/CameraServer.cpp b/cameraserver/src/main/native/cpp/cameraserver/CameraServer.cpp index dec1460241..2302b1abaf 100644 --- a/cameraserver/src/main/native/cpp/cameraserver/CameraServer.cpp +++ b/cameraserver/src/main/native/cpp/cameraserver/CameraServer.cpp @@ -87,7 +87,7 @@ static std::string MakeStreamValue(const wpi::Twine& address, int port) { std::shared_ptr CameraServer::Impl::GetSourceTable( CS_Source source) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); return m_tables.lookup(source); } @@ -153,7 +153,7 @@ std::vector CameraServer::Impl::GetSourceStreamValues( } void CameraServer::Impl::UpdateStreamValues() { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); // Over all the sinks... for (const auto& i : m_sinks) { CS_Status status = 0; @@ -299,7 +299,7 @@ CameraServer::Impl::Impl() // Create subtable for the camera auto table = m_publishTable->GetSubTable(event.name); { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_tables.insert(std::make_pair(event.sourceHandle, table)); } wpi::SmallString<64> buf; @@ -564,7 +564,7 @@ cs::CvSink CameraServer::GetVideo() { cs::VideoSource source; { auto csShared = GetCameraServerShared(); - std::lock_guard lock(m_impl->m_mutex); + std::scoped_lock lock(m_impl->m_mutex); if (m_impl->m_primarySourceName.empty()) { csShared->SetCameraServerError("no camera available"); return cs::CvSink{}; @@ -584,7 +584,7 @@ cs::CvSink CameraServer::GetVideo(const cs::VideoSource& camera) { name += camera.GetName(); { - std::lock_guard lock(m_impl->m_mutex); + std::scoped_lock lock(m_impl->m_mutex); auto it = m_impl->m_sinks.find(name); if (it != m_impl->m_sinks.end()) { auto kind = it->second.GetKind(); @@ -609,7 +609,7 @@ cs::CvSink CameraServer::GetVideo(const wpi::Twine& name) { wpi::StringRef nameStr = name.toStringRef(nameBuf); cs::VideoSource source; { - std::lock_guard lock(m_impl->m_mutex); + std::scoped_lock lock(m_impl->m_mutex); auto it = m_impl->m_sources.find(nameStr); if (it == m_impl->m_sources.end()) { auto csShared = GetCameraServerShared(); @@ -631,7 +631,7 @@ cs::CvSource CameraServer::PutVideo(const wpi::Twine& name, int width, cs::MjpegServer CameraServer::AddServer(const wpi::Twine& name) { int port; { - std::lock_guard lock(m_impl->m_mutex); + std::scoped_lock lock(m_impl->m_mutex); port = m_impl->m_nextPort++; } return AddServer(name, port); @@ -644,12 +644,12 @@ cs::MjpegServer CameraServer::AddServer(const wpi::Twine& name, int port) { } void CameraServer::AddServer(const cs::VideoSink& server) { - std::lock_guard lock(m_impl->m_mutex); + std::scoped_lock lock(m_impl->m_mutex); m_impl->m_sinks.try_emplace(server.GetName(), server); } void CameraServer::RemoveServer(const wpi::Twine& name) { - std::lock_guard lock(m_impl->m_mutex); + std::scoped_lock lock(m_impl->m_mutex); wpi::SmallString<64> nameBuf; m_impl->m_sinks.erase(name.toStringRef(nameBuf)); } @@ -657,7 +657,7 @@ void CameraServer::RemoveServer(const wpi::Twine& name) { cs::VideoSink CameraServer::GetServer() { wpi::SmallString<64> name; { - std::lock_guard lock(m_impl->m_mutex); + std::scoped_lock lock(m_impl->m_mutex); if (m_impl->m_primarySourceName.empty()) { auto csShared = GetCameraServerShared(); csShared->SetCameraServerError("no camera available"); @@ -672,7 +672,7 @@ cs::VideoSink CameraServer::GetServer() { cs::VideoSink CameraServer::GetServer(const wpi::Twine& name) { wpi::SmallString<64> nameBuf; wpi::StringRef nameStr = name.toStringRef(nameBuf); - std::lock_guard lock(m_impl->m_mutex); + std::scoped_lock lock(m_impl->m_mutex); auto it = m_impl->m_sinks.find(nameStr); if (it == m_impl->m_sinks.end()) { auto csShared = GetCameraServerShared(); @@ -684,19 +684,19 @@ cs::VideoSink CameraServer::GetServer(const wpi::Twine& name) { void CameraServer::AddCamera(const cs::VideoSource& camera) { std::string name = camera.GetName(); - std::lock_guard lock(m_impl->m_mutex); + std::scoped_lock lock(m_impl->m_mutex); if (m_impl->m_primarySourceName.empty()) m_impl->m_primarySourceName = name; m_impl->m_sources.try_emplace(name, camera); } void CameraServer::RemoveCamera(const wpi::Twine& name) { - std::lock_guard lock(m_impl->m_mutex); + std::scoped_lock lock(m_impl->m_mutex); wpi::SmallString<64> nameBuf; m_impl->m_sources.erase(name.toStringRef(nameBuf)); } void CameraServer::SetSize(int size) { - std::lock_guard lock(m_impl->m_mutex); + std::scoped_lock lock(m_impl->m_mutex); if (m_impl->m_primarySourceName.empty()) return; auto it = m_impl->m_sources.find(m_impl->m_primarySourceName); if (it == m_impl->m_sources.end()) return; diff --git a/cscore/src/main/native/cpp/ConfigurableSourceImpl.cpp b/cscore/src/main/native/cpp/ConfigurableSourceImpl.cpp index fc00582e1c..b9741696e7 100644 --- a/cscore/src/main/native/cpp/ConfigurableSourceImpl.cpp +++ b/cscore/src/main/native/cpp/ConfigurableSourceImpl.cpp @@ -37,7 +37,7 @@ void ConfigurableSourceImpl::Start() { bool ConfigurableSourceImpl::SetVideoMode(const VideoMode& mode, CS_Status* status) { { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_mode = mode; m_videoModes[0] = mode; } @@ -61,7 +61,7 @@ int ConfigurableSourceImpl::CreateProperty(const wpi::Twine& name, CS_PropertyKind kind, int minimum, int maximum, int step, int defaultValue, int value) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); int ndx = CreateOrUpdateProperty(name, [=] { return std::make_unique( @@ -92,7 +92,7 @@ int ConfigurableSourceImpl::CreateProperty( void ConfigurableSourceImpl::SetEnumPropertyChoices( int property, wpi::ArrayRef choices, CS_Status* status) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) { *status = CS_INVALID_PROPERTY; diff --git a/cscore/src/main/native/cpp/Frame.cpp b/cscore/src/main/native/cpp/Frame.cpp index 5833ce96fa..5dd650ec9c 100644 --- a/cscore/src/main/native/cpp/Frame.cpp +++ b/cscore/src/main/native/cpp/Frame.cpp @@ -36,7 +36,7 @@ Frame::Frame(SourceImpl& source, std::unique_ptr image, Time time) Image* Frame::GetNearestImage(int width, int height) const { if (!m_impl) return nullptr; - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); Image* found = nullptr; // Ideally we want the smallest image at least width/height in size @@ -60,7 +60,7 @@ Image* Frame::GetNearestImage(int width, int height, VideoMode::PixelFormat pixelFormat, int jpegQuality) const { if (!m_impl) return nullptr; - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); Image* found = nullptr; // We want the smallest image at least width/height (or the next largest), @@ -253,7 +253,7 @@ Image* Frame::ConvertMJPEGToBGR(Image* image) { // Save the result Image* rv = newImage.release(); if (m_impl) { - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); m_impl->images.push_back(rv); } return rv; @@ -274,7 +274,7 @@ Image* Frame::ConvertMJPEGToGray(Image* image) { // Save the result Image* rv = newImage.release(); if (m_impl) { - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); m_impl->images.push_back(rv); } return rv; @@ -294,7 +294,7 @@ Image* Frame::ConvertYUYVToBGR(Image* image) { // Save the result Image* rv = newImage.release(); if (m_impl) { - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); m_impl->images.push_back(rv); } return rv; @@ -314,7 +314,7 @@ Image* Frame::ConvertBGRToRGB565(Image* image) { // Save the result Image* rv = newImage.release(); if (m_impl) { - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); m_impl->images.push_back(rv); } return rv; @@ -334,7 +334,7 @@ Image* Frame::ConvertRGB565ToBGR(Image* image) { // Save the result Image* rv = newImage.release(); if (m_impl) { - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); m_impl->images.push_back(rv); } return rv; @@ -354,7 +354,7 @@ Image* Frame::ConvertBGRToGray(Image* image) { // Save the result Image* rv = newImage.release(); if (m_impl) { - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); m_impl->images.push_back(rv); } return rv; @@ -374,7 +374,7 @@ Image* Frame::ConvertGrayToBGR(Image* image) { // Save the result Image* rv = newImage.release(); if (m_impl) { - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); m_impl->images.push_back(rv); } return rv; @@ -383,7 +383,7 @@ Image* Frame::ConvertGrayToBGR(Image* image) { Image* Frame::ConvertBGRToMJPEG(Image* image, int quality) { if (!image || image->pixelFormat != VideoMode::kBGR) return nullptr; if (!m_impl) return nullptr; - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); // Allocate a JPEG image. We don't actually know what the resulting size // will be; while the destination will automatically grow, doing so will @@ -414,7 +414,7 @@ Image* Frame::ConvertBGRToMJPEG(Image* image, int quality) { Image* Frame::ConvertGrayToMJPEG(Image* image, int quality) { if (!image || image->pixelFormat != VideoMode::kGray) return nullptr; if (!m_impl) return nullptr; - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); // Allocate a JPEG image. We don't actually know what the resulting size // will be; while the destination will automatically grow, doing so will @@ -446,7 +446,7 @@ Image* Frame::GetImageImpl(int width, int height, VideoMode::PixelFormat pixelFormat, int requiredJpegQuality, int defaultJpegQuality) { if (!m_impl) return nullptr; - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); Image* cur = GetNearestImage(width, height, pixelFormat, requiredJpegQuality); if (!cur || cur->Is(width, height, pixelFormat, requiredJpegQuality)) return cur; diff --git a/cscore/src/main/native/cpp/Frame.h b/cscore/src/main/native/cpp/Frame.h index 4dc6e50213..07fa24fd0f 100644 --- a/cscore/src/main/native/cpp/Frame.h +++ b/cscore/src/main/native/cpp/Frame.h @@ -80,42 +80,42 @@ class Frame { int GetOriginalWidth() const { if (!m_impl) return 0; - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); if (m_impl->images.empty()) return 0; return m_impl->images[0]->width; } int GetOriginalHeight() const { if (!m_impl) return 0; - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); if (m_impl->images.empty()) return 0; return m_impl->images[0]->height; } int GetOriginalPixelFormat() const { if (!m_impl) return 0; - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); if (m_impl->images.empty()) return 0; return m_impl->images[0]->pixelFormat; } int GetOriginalJpegQuality() const { if (!m_impl) return 0; - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); if (m_impl->images.empty()) return 0; return m_impl->images[0]->jpegQuality; } Image* GetExistingImage(size_t i = 0) const { if (!m_impl) return nullptr; - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); if (i >= m_impl->images.size()) return nullptr; return m_impl->images[i]; } Image* GetExistingImage(int width, int height) const { if (!m_impl) return nullptr; - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); for (auto i : m_impl->images) { if (i->Is(width, height)) return i; } @@ -125,7 +125,7 @@ class Frame { Image* GetExistingImage(int width, int height, VideoMode::PixelFormat pixelFormat) const { if (!m_impl) return nullptr; - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); for (auto i : m_impl->images) { if (i->Is(width, height, pixelFormat)) return i; } @@ -136,7 +136,7 @@ class Frame { VideoMode::PixelFormat pixelFormat, int jpegQuality) const { if (!m_impl) return nullptr; - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); for (auto i : m_impl->images) { if (i->Is(width, height, pixelFormat, jpegQuality)) return i; } diff --git a/cscore/src/main/native/cpp/HttpCameraImpl.cpp b/cscore/src/main/native/cpp/HttpCameraImpl.cpp index 642dedddb2..5bf7a8ab37 100644 --- a/cscore/src/main/native/cpp/HttpCameraImpl.cpp +++ b/cscore/src/main/native/cpp/HttpCameraImpl.cpp @@ -37,7 +37,7 @@ HttpCameraImpl::~HttpCameraImpl() { // Close file if it's open { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (m_streamConn) m_streamConn->stream->close(); if (m_settingsConn) m_settingsConn->stream->close(); } @@ -131,7 +131,7 @@ wpi::HttpConnection* HttpCameraImpl::DeviceStreamConnect( // Build the request wpi::HttpRequest req; { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (m_locations.empty()) { SERROR("locations array is empty!?"); std::this_thread::sleep_for(std::chrono::seconds(1)); @@ -153,7 +153,7 @@ wpi::HttpConnection* HttpCameraImpl::DeviceStreamConnect( // update m_streamConn { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_frameCount = 1; // avoid a race with monitor thread m_streamConn = std::move(connPtr); } @@ -161,7 +161,7 @@ wpi::HttpConnection* HttpCameraImpl::DeviceStreamConnect( std::string warn; if (!conn->Handshake(req, &warn)) { SWARNING(GetName() << ": " << warn); - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_streamConn = nullptr; return nullptr; } @@ -173,7 +173,7 @@ wpi::HttpConnection* HttpCameraImpl::DeviceStreamConnect( if (mediaType != "multipart/x-mixed-replace") { SWARNING("\"" << req.host << "\": unrecognized Content-Type \"" << mediaType << "\""); - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_streamConn = nullptr; return nullptr; } @@ -198,7 +198,7 @@ wpi::HttpConnection* HttpCameraImpl::DeviceStreamConnect( if (boundary.empty()) { SWARNING("\"" << req.host << "\": empty multi-part boundary or no Content-Type"); - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_streamConn = nullptr; return nullptr; } @@ -326,7 +326,7 @@ void HttpCameraImpl::DeviceSendSettings(wpi::HttpRequest& req) { // update m_settingsConn { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_settingsConn = std::move(connPtr); } @@ -338,7 +338,7 @@ void HttpCameraImpl::DeviceSendSettings(wpi::HttpRequest& req) { } CS_HttpCameraKind HttpCameraImpl::GetKind() const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); return m_kind; } @@ -356,7 +356,7 @@ bool HttpCameraImpl::SetUrls(wpi::ArrayRef urls, } } - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_locations.swap(locations); m_nextLocation = 0; m_streamSettingsUpdated = true; @@ -364,7 +364,7 @@ bool HttpCameraImpl::SetUrls(wpi::ArrayRef urls, } std::vector HttpCameraImpl::GetUrls() const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); std::vector urls; for (const auto& loc : m_locations) urls.push_back(loc.url); return urls; @@ -375,7 +375,7 @@ void HttpCameraImpl::CreateProperty(const wpi::Twine& name, bool viaSettings, CS_PropertyKind kind, int minimum, int maximum, int step, int defaultValue, int value) const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_propertyData.emplace_back(std::make_unique( name, httpParam, viaSettings, kind, minimum, maximum, step, defaultValue, value)); @@ -389,7 +389,7 @@ template void HttpCameraImpl::CreateEnumProperty( const wpi::Twine& name, const wpi::Twine& httpParam, bool viaSettings, int defaultValue, int value, std::initializer_list choices) const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_propertyData.emplace_back(std::make_unique( name, httpParam, viaSettings, CS_PROP_ENUM, 0, choices.size() - 1, 1, defaultValue, value)); @@ -412,7 +412,7 @@ std::unique_ptr HttpCameraImpl::CreateEmptyProperty( } bool HttpCameraImpl::CacheProperties(CS_Status* status) const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); // Pretty typical set of video modes m_videoModes.clear(); @@ -468,7 +468,7 @@ void HttpCameraImpl::SetExposureManual(int value, CS_Status* status) { bool HttpCameraImpl::SetVideoMode(const VideoMode& mode, CS_Status* status) { if (mode.pixelFormat != VideoMode::kMJPEG) return false; - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_mode = mode; m_streamSettingsUpdated = true; return true; @@ -497,7 +497,7 @@ bool AxisCameraImpl::CacheProperties(CS_Status* status) const { true, CS_PROP_INTEGER, 0, 100, 1, 50, 50); // TODO: get video modes from device - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_videoModes.clear(); m_videoModes.emplace_back(VideoMode::kMJPEG, 640, 480, 30); m_videoModes.emplace_back(VideoMode::kMJPEG, 480, 360, 30); diff --git a/cscore/src/main/native/cpp/MjpegServerImpl.cpp b/cscore/src/main/native/cpp/MjpegServerImpl.cpp index 2ed2575b49..e30b745299 100644 --- a/cscore/src/main/native/cpp/MjpegServerImpl.cpp +++ b/cscore/src/main/native/cpp/MjpegServerImpl.cpp @@ -105,18 +105,18 @@ class MjpegServerImpl::ConnThread : public wpi::SafeThread { wpi::StringRef GetName() { return m_name; } std::shared_ptr GetSource() { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); return m_source; } void StartStream() { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (m_source) m_source->EnableSink(); m_streaming = true; } void StopStream() { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (m_source) m_source->DisableSink(); m_streaming = false; } @@ -898,7 +898,7 @@ void MjpegServerImpl::ServerThreadMain() { auto source = GetSource(); - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); // Find unoccupied worker thread, or create one if necessary auto it = std::find_if(m_connThreads.begin(), m_connThreads.end(), [](const wpi::SafeThreadOwner& owner) { @@ -937,7 +937,7 @@ void MjpegServerImpl::ServerThreadMain() { } void MjpegServerImpl::SetSourceImpl(std::shared_ptr source) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); for (auto& connThread : m_connThreads) { if (auto thr = connThread.GetThread()) { if (thr->m_source != source) { diff --git a/cscore/src/main/native/cpp/PropertyContainer.cpp b/cscore/src/main/native/cpp/PropertyContainer.cpp index 88ce2291e9..17bf94be54 100644 --- a/cscore/src/main/native/cpp/PropertyContainer.cpp +++ b/cscore/src/main/native/cpp/PropertyContainer.cpp @@ -18,7 +18,7 @@ int PropertyContainer::GetPropertyIndex(const wpi::Twine& name) const { // We can't fail, so instead we create a new index if caching fails. CS_Status status = 0; if (!m_properties_cached) CacheProperties(&status); - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); wpi::SmallVector nameBuf; int& ndx = m_properties[name.toStringRef(nameBuf)]; if (ndx == 0) { @@ -33,7 +33,7 @@ wpi::ArrayRef PropertyContainer::EnumerateProperties( wpi::SmallVectorImpl& vec, CS_Status* status) const { if (!m_properties_cached && !CacheProperties(status)) return wpi::ArrayRef{}; - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); for (int i = 0; i < static_cast(m_propertyData.size()); ++i) { if (m_propertyData[i]) vec.push_back(i + 1); } @@ -43,7 +43,7 @@ wpi::ArrayRef PropertyContainer::EnumerateProperties( CS_PropertyKind PropertyContainer::GetPropertyKind(int property) const { CS_Status status = 0; if (!m_properties_cached && !CacheProperties(&status)) return CS_PROP_NONE; - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) return CS_PROP_NONE; return prop->propKind; @@ -52,7 +52,7 @@ CS_PropertyKind PropertyContainer::GetPropertyKind(int property) const { wpi::StringRef PropertyContainer::GetPropertyName( int property, wpi::SmallVectorImpl& buf, CS_Status* status) const { if (!m_properties_cached && !CacheProperties(status)) return wpi::StringRef{}; - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) { *status = CS_INVALID_PROPERTY; @@ -64,7 +64,7 @@ wpi::StringRef PropertyContainer::GetPropertyName( int PropertyContainer::GetProperty(int property, CS_Status* status) const { if (!m_properties_cached && !CacheProperties(status)) return 0; - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) { *status = CS_INVALID_PROPERTY; @@ -80,7 +80,7 @@ int PropertyContainer::GetProperty(int property, CS_Status* status) const { void PropertyContainer::SetProperty(int property, int value, CS_Status* status) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) { *status = CS_INVALID_PROPERTY; @@ -101,7 +101,7 @@ void PropertyContainer::SetProperty(int property, int value, int PropertyContainer::GetPropertyMin(int property, CS_Status* status) const { if (!m_properties_cached && !CacheProperties(status)) return 0; - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) { *status = CS_INVALID_PROPERTY; @@ -112,7 +112,7 @@ int PropertyContainer::GetPropertyMin(int property, CS_Status* status) const { int PropertyContainer::GetPropertyMax(int property, CS_Status* status) const { if (!m_properties_cached && !CacheProperties(status)) return 0; - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) { *status = CS_INVALID_PROPERTY; @@ -123,7 +123,7 @@ int PropertyContainer::GetPropertyMax(int property, CS_Status* status) const { int PropertyContainer::GetPropertyStep(int property, CS_Status* status) const { if (!m_properties_cached && !CacheProperties(status)) return 0; - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) { *status = CS_INVALID_PROPERTY; @@ -135,7 +135,7 @@ int PropertyContainer::GetPropertyStep(int property, CS_Status* status) const { int PropertyContainer::GetPropertyDefault(int property, CS_Status* status) const { if (!m_properties_cached && !CacheProperties(status)) return 0; - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) { *status = CS_INVALID_PROPERTY; @@ -147,7 +147,7 @@ int PropertyContainer::GetPropertyDefault(int property, wpi::StringRef PropertyContainer::GetStringProperty( int property, wpi::SmallVectorImpl& buf, CS_Status* status) const { if (!m_properties_cached && !CacheProperties(status)) return wpi::StringRef{}; - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) { *status = CS_INVALID_PROPERTY; @@ -164,7 +164,7 @@ wpi::StringRef PropertyContainer::GetStringProperty( void PropertyContainer::SetStringProperty(int property, const wpi::Twine& value, CS_Status* status) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) { *status = CS_INVALID_PROPERTY; @@ -186,7 +186,7 @@ std::vector PropertyContainer::GetEnumPropertyChoices( int property, CS_Status* status) const { if (!m_properties_cached && !CacheProperties(status)) return std::vector{}; - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); if (!prop) { *status = CS_INVALID_PROPERTY; diff --git a/cscore/src/main/native/cpp/SinkImpl.cpp b/cscore/src/main/native/cpp/SinkImpl.cpp index 5b979e62d3..5d4235a60d 100644 --- a/cscore/src/main/native/cpp/SinkImpl.cpp +++ b/cscore/src/main/native/cpp/SinkImpl.cpp @@ -30,18 +30,18 @@ SinkImpl::~SinkImpl() { } void SinkImpl::SetDescription(const wpi::Twine& description) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_description = description.str(); } wpi::StringRef SinkImpl::GetDescription(wpi::SmallVectorImpl& buf) const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); buf.append(m_description.begin(), m_description.end()); return wpi::StringRef{buf.data(), buf.size()}; } void SinkImpl::Enable() { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); ++m_enabledCount; if (m_enabledCount == 1) { if (m_source) m_source->EnableSink(); @@ -50,7 +50,7 @@ void SinkImpl::Enable() { } void SinkImpl::Disable() { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); --m_enabledCount; if (m_enabledCount == 0) { if (m_source) m_source->DisableSink(); @@ -59,7 +59,7 @@ void SinkImpl::Disable() { } void SinkImpl::SetEnabled(bool enabled) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (enabled && m_enabledCount == 0) { if (m_source) m_source->EnableSink(); m_enabledCount = 1; @@ -73,7 +73,7 @@ void SinkImpl::SetEnabled(bool enabled) { void SinkImpl::SetSource(std::shared_ptr source) { { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (m_source == source) return; if (m_source) { if (m_enabledCount > 0) m_source->DisableSink(); @@ -89,13 +89,13 @@ void SinkImpl::SetSource(std::shared_ptr source) { } std::string SinkImpl::GetError() const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (!m_source) return "no source connected"; return m_source->GetCurFrame().GetError(); } wpi::StringRef SinkImpl::GetError(wpi::SmallVectorImpl& buf) const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (!m_source) return "no source connected"; // Make a copy as it's shared data wpi::StringRef error = m_source->GetCurFrame().GetError(); diff --git a/cscore/src/main/native/cpp/SinkImpl.h b/cscore/src/main/native/cpp/SinkImpl.h index 9a1ebbbc44..7ad831f76c 100644 --- a/cscore/src/main/native/cpp/SinkImpl.h +++ b/cscore/src/main/native/cpp/SinkImpl.h @@ -48,7 +48,7 @@ class SinkImpl : public PropertyContainer { void SetSource(std::shared_ptr source); std::shared_ptr GetSource() const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); return m_source; } diff --git a/cscore/src/main/native/cpp/SourceImpl.cpp b/cscore/src/main/native/cpp/SourceImpl.cpp index 870da68797..455b6cd05d 100644 --- a/cscore/src/main/native/cpp/SourceImpl.cpp +++ b/cscore/src/main/native/cpp/SourceImpl.cpp @@ -44,13 +44,13 @@ SourceImpl::~SourceImpl() { } void SourceImpl::SetDescription(const wpi::Twine& description) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_description = description.str(); } wpi::StringRef SourceImpl::GetDescription( wpi::SmallVectorImpl& buf) const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); buf.append(m_description.begin(), m_description.end()); return wpi::StringRef{buf.data(), buf.size()}; } @@ -93,7 +93,7 @@ Frame SourceImpl::GetNextFrame(double timeout) { void SourceImpl::Wakeup() { { - std::lock_guard lock{m_frameMutex}; + std::scoped_lock lock{m_frameMutex}; m_frame = Frame{*this, wpi::StringRef{}, 0}; } m_frameCv.notify_all(); @@ -134,7 +134,7 @@ void SourceImpl::SetExposureManual(int value, CS_Status* status) { VideoMode SourceImpl::GetVideoMode(CS_Status* status) const { if (!m_properties_cached && !CacheProperties(status)) return VideoMode{}; - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); return m_mode; } @@ -380,7 +380,7 @@ std::vector SourceImpl::EnumerateVideoModes( CS_Status* status) const { if (!m_properties_cached && !CacheProperties(status)) return std::vector{}; - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); return m_videoModes; } @@ -388,7 +388,7 @@ std::unique_ptr SourceImpl::AllocImage( VideoMode::PixelFormat pixelFormat, int width, int height, size_t size) { std::unique_ptr image; { - std::lock_guard lock{m_poolMutex}; + std::scoped_lock lock{m_poolMutex}; // find the smallest existing frame that is at least big enough. int found = -1; for (size_t i = 0; i < m_imagesAvail.size(); ++i) { @@ -440,7 +440,7 @@ void SourceImpl::PutFrame(std::unique_ptr image, Frame::Time time) { // Update frame { - std::lock_guard lock{m_frameMutex}; + std::scoped_lock lock{m_frameMutex}; m_frame = Frame{*this, std::move(image), time}; } @@ -451,7 +451,7 @@ void SourceImpl::PutFrame(std::unique_ptr image, Frame::Time time) { void SourceImpl::PutError(const wpi::Twine& msg, Frame::Time time) { // Update frame { - std::lock_guard lock{m_frameMutex}; + std::scoped_lock lock{m_frameMutex}; m_frame = Frame{*this, msg, time}; } @@ -489,7 +489,7 @@ void SourceImpl::UpdatePropertyValue(int property, bool setString, int value, } void SourceImpl::ReleaseImage(std::unique_ptr image) { - std::lock_guard lock{m_poolMutex}; + std::scoped_lock lock{m_poolMutex}; if (m_destroyFrames) return; // Return the frame to the pool. First try to find an empty slot, otherwise // add it to the end. @@ -511,7 +511,7 @@ void SourceImpl::ReleaseImage(std::unique_ptr image) { } std::unique_ptr SourceImpl::AllocFrameImpl() { - std::lock_guard lock{m_poolMutex}; + std::scoped_lock lock{m_poolMutex}; if (m_framesAvail.empty()) return std::make_unique(*this); @@ -521,7 +521,7 @@ std::unique_ptr SourceImpl::AllocFrameImpl() { } void SourceImpl::ReleaseFrameImpl(std::unique_ptr impl) { - std::lock_guard lock{m_poolMutex}; + std::scoped_lock lock{m_poolMutex}; if (m_destroyFrames) return; m_framesAvail.push_back(std::move(impl)); } diff --git a/cscore/src/main/native/cpp/UnlimitedHandleResource.h b/cscore/src/main/native/cpp/UnlimitedHandleResource.h index 4e189d9e31..6c9a538eaa 100644 --- a/cscore/src/main/native/cpp/UnlimitedHandleResource.h +++ b/cscore/src/main/native/cpp/UnlimitedHandleResource.h @@ -78,7 +78,7 @@ template template THandle UnlimitedHandleResource::Allocate( Args&&... args) { - std::lock_guard sync(m_handleMutex); + std::scoped_lock sync(m_handleMutex); size_t i; for (i = 0; i < m_structures.size(); i++) { if (m_structures[i] == nullptr) { @@ -96,7 +96,7 @@ THandle UnlimitedHandleResource::Allocate( template THandle UnlimitedHandleResource::Allocate( std::shared_ptr structure) { - std::lock_guard sync(m_handleMutex); + std::scoped_lock sync(m_handleMutex); size_t i; for (i = 0; i < m_structures.size(); i++) { if (m_structures[i] == nullptr) { @@ -117,7 +117,7 @@ UnlimitedHandleResource::Get( auto index = handle.GetTypedIndex(static_cast(typeValue)); if (index < 0) return nullptr; - std::lock_guard sync(m_handleMutex); + std::scoped_lock sync(m_handleMutex); if (index >= static_cast(m_structures.size())) return nullptr; return m_structures[index]; } @@ -129,7 +129,7 @@ UnlimitedHandleResource::Free( auto index = handle.GetTypedIndex(static_cast(typeValue)); if (index < 0) return nullptr; - std::lock_guard sync(m_handleMutex); + std::scoped_lock sync(m_handleMutex); if (index >= static_cast(m_structures.size())) return nullptr; auto rv = std::move(m_structures[index]); m_structures[index].reset(); @@ -148,7 +148,7 @@ UnlimitedHandleResource::GetAll( template inline std::vector> UnlimitedHandleResource::FreeAll() { - std::lock_guard sync(m_handleMutex); + std::scoped_lock sync(m_handleMutex); auto rv = std::move(m_structures); m_structures.clear(); return rv; @@ -158,7 +158,7 @@ template template inline void UnlimitedHandleResource::ForEach(F func) { - std::lock_guard sync(m_handleMutex); + std::scoped_lock sync(m_handleMutex); for (size_t i = 0; i < m_structures.size(); i++) { if (m_structures[i] != nullptr) func(MakeHandle(i), *(m_structures[i])); } @@ -168,7 +168,7 @@ template template inline std::pair> UnlimitedHandleResource::FindIf(F func) { - std::lock_guard sync(m_handleMutex); + std::scoped_lock sync(m_handleMutex); for (size_t i = 0; i < m_structures.size(); i++) { auto& structure = m_structures[i]; if (structure != nullptr && func(*structure)) diff --git a/cscore/src/main/native/linux/UsbCameraImpl.cpp b/cscore/src/main/native/linux/UsbCameraImpl.cpp index 7d0e338cfc..13f7a43229 100644 --- a/cscore/src/main/native/linux/UsbCameraImpl.cpp +++ b/cscore/src/main/native/linux/UsbCameraImpl.cpp @@ -815,7 +815,7 @@ void UsbCameraImpl::DeviceCacheMode() { vfmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (DoIoctl(fd, VIDIOC_G_FMT, &vfmt) != 0) { SERROR("could not read current video mode"); - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_mode = VideoMode{VideoMode::kMJPEG, 320, 240, 30}; return; } @@ -881,7 +881,7 @@ void UsbCameraImpl::DeviceCacheMode() { // Save to global mode { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_mode.pixelFormat = pixelFormat; m_mode.width = width; m_mode.height = height; @@ -1070,7 +1070,7 @@ void UsbCameraImpl::DeviceCacheVideoModes() { } { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_videoModes.swap(modes); } m_notifier.NotifySource(*this, CS_SOURCE_VIDEOMODES_UPDATED); @@ -1085,7 +1085,7 @@ CS_StatusValue UsbCameraImpl::SendAndWait(Message&& msg) const { // Add the message to the command queue { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_commands.emplace_back(std::move(msg)); } @@ -1120,7 +1120,7 @@ void UsbCameraImpl::Send(Message&& msg) const { // Add the message to the command queue { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_commands.emplace_back(std::move(msg)); } diff --git a/cscore/src/main/native/windows/UsbCameraImpl.cpp b/cscore/src/main/native/windows/UsbCameraImpl.cpp index 9ec0580c07..69c1fcb2e3 100644 --- a/cscore/src/main/native/windows/UsbCameraImpl.cpp +++ b/cscore/src/main/native/windows/UsbCameraImpl.cpp @@ -875,10 +875,10 @@ void UsbCameraImpl::DeviceCacheMode() { // Default mode is not supported. Grab first supported image auto&& firstSupported = m_windowsVideoModes[0]; m_currentMode = firstSupported.second; - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_mode = firstSupported.first; } else { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_mode = result->first; } } @@ -960,7 +960,7 @@ void UsbCameraImpl::DeviceCacheVideoModes() { count++; } { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_videoModes.swap(modes); } m_notifier.NotifySource(*this, CS_SOURCE_VIDEOMODES_UPDATED); diff --git a/hal/src/main/native/athena/AnalogInput.cpp b/hal/src/main/native/athena/AnalogInput.cpp index 6e79e77a6b..8838149ed6 100644 --- a/hal/src/main/native/athena/AnalogInput.cpp +++ b/hal/src/main/native/athena/AnalogInput.cpp @@ -149,7 +149,7 @@ int32_t HAL_GetAnalogValue(HAL_AnalogInputHandle analogPortHandle, readSelect.Channel = port->channel; readSelect.Averaged = false; - std::lock_guard lock(analogRegisterWindowMutex); + std::scoped_lock lock(analogRegisterWindowMutex); analogInputSystem->writeReadSelect(readSelect, status); analogInputSystem->strobeLatchOutput(status); return static_cast(analogInputSystem->readOutput(status)); @@ -166,7 +166,7 @@ int32_t HAL_GetAnalogAverageValue(HAL_AnalogInputHandle analogPortHandle, readSelect.Channel = port->channel; readSelect.Averaged = true; - std::lock_guard lock(analogRegisterWindowMutex); + std::scoped_lock lock(analogRegisterWindowMutex); analogInputSystem->writeReadSelect(readSelect, status); analogInputSystem->strobeLatchOutput(status); return static_cast(analogInputSystem->readOutput(status)); diff --git a/hal/src/main/native/athena/AnalogInternal.cpp b/hal/src/main/native/athena/AnalogInternal.cpp index 0083b614c9..03a246d15b 100644 --- a/hal/src/main/native/athena/AnalogInternal.cpp +++ b/hal/src/main/native/athena/AnalogInternal.cpp @@ -44,7 +44,7 @@ void InitializeAnalogInternal() { void initializeAnalog(int32_t* status) { hal::init::CheckInit(); if (analogSystemInitialized) return; - std::lock_guard lock(analogRegisterWindowMutex); + std::scoped_lock lock(analogRegisterWindowMutex); if (analogSystemInitialized) return; analogInputSystem.reset(tAI::create(status)); analogOutputSystem.reset(tAO::create(status)); diff --git a/hal/src/main/native/athena/CANAPI.cpp b/hal/src/main/native/athena/CANAPI.cpp index 8944a98e43..aa41224f84 100644 --- a/hal/src/main/native/athena/CANAPI.cpp +++ b/hal/src/main/native/athena/CANAPI.cpp @@ -91,7 +91,7 @@ HAL_CANHandle HAL_InitializeCAN(HAL_CANManufacturer manufacturer, void HAL_CleanCAN(HAL_CANHandle handle) { auto data = canHandles->Free(handle); - std::lock_guard lock(data->mapMutex); + std::scoped_lock lock(data->mapMutex); for (auto&& i : data->periodicSends) { int32_t s = 0; @@ -115,7 +115,7 @@ void HAL_WriteCANPacket(HAL_CANHandle handle, const uint8_t* data, if (*status != 0) { return; } - std::lock_guard lock(can->mapMutex); + std::scoped_lock lock(can->mapMutex); can->periodicSends[apiId] = -1; } @@ -134,7 +134,7 @@ void HAL_WriteCANPacketRepeating(HAL_CANHandle handle, const uint8_t* data, if (*status != 0) { return; } - std::lock_guard lock(can->mapMutex); + std::scoped_lock lock(can->mapMutex); can->periodicSends[apiId] = repeatMs; } @@ -153,7 +153,7 @@ void HAL_StopCANPacketRepeating(HAL_CANHandle handle, int32_t apiId, if (*status != 0) { return; } - std::lock_guard lock(can->mapMutex); + std::scoped_lock lock(can->mapMutex); can->periodicSends[apiId] = -1; } @@ -172,7 +172,7 @@ void HAL_ReadCANPacketNew(HAL_CANHandle handle, int32_t apiId, uint8_t* data, HAL_CAN_ReceiveMessage(&messageId, 0x1FFFFFFF, data, &dataSize, &ts, status); if (*status == 0) { - std::lock_guard lock(can->mapMutex); + std::scoped_lock lock(can->mapMutex); auto& msg = can->receives[messageId]; msg.length = dataSize; msg.lastTimeStamp = ts; @@ -197,7 +197,7 @@ void HAL_ReadCANPacketLatest(HAL_CANHandle handle, int32_t apiId, uint8_t* data, uint32_t ts = 0; HAL_CAN_ReceiveMessage(&messageId, 0x1FFFFFFF, data, &dataSize, &ts, status); - std::lock_guard lock(can->mapMutex); + std::scoped_lock lock(can->mapMutex); if (*status == 0) { // fresh update auto& msg = can->receives[messageId]; @@ -234,7 +234,7 @@ void HAL_ReadCANPacketTimeout(HAL_CANHandle handle, int32_t apiId, uint32_t ts = 0; HAL_CAN_ReceiveMessage(&messageId, 0x1FFFFFFF, data, &dataSize, &ts, status); - std::lock_guard lock(can->mapMutex); + std::scoped_lock lock(can->mapMutex); if (*status == 0) { // fresh update auto& msg = can->receives[messageId]; @@ -276,7 +276,7 @@ void HAL_ReadCANPeriodicPacket(HAL_CANHandle handle, int32_t apiId, uint32_t messageId = CreateCANId(can.get(), apiId); { - std::lock_guard lock(can->mapMutex); + std::scoped_lock lock(can->mapMutex); auto i = can->receives.find(messageId); if (i != can->receives.end()) { // Found, check if new enough @@ -296,7 +296,7 @@ void HAL_ReadCANPeriodicPacket(HAL_CANHandle handle, int32_t apiId, uint32_t ts = 0; HAL_CAN_ReceiveMessage(&messageId, 0x1FFFFFFF, data, &dataSize, &ts, status); - std::lock_guard lock(can->mapMutex); + std::scoped_lock lock(can->mapMutex); if (*status == 0) { // fresh update auto& msg = can->receives[messageId]; diff --git a/hal/src/main/native/athena/DIO.cpp b/hal/src/main/native/athena/DIO.cpp index fdc24b81a5..56b096392b 100644 --- a/hal/src/main/native/athena/DIO.cpp +++ b/hal/src/main/native/athena/DIO.cpp @@ -69,7 +69,7 @@ HAL_DigitalHandle HAL_InitializeDIOPort(HAL_PortHandle portHandle, port->channel = static_cast(channel); - std::lock_guard lock(digitalDIOMutex); + std::scoped_lock lock(digitalDIOMutex); tDIO::tOutputEnable outputEnable = digitalSystem->readOutputEnable(status); @@ -143,7 +143,7 @@ void HAL_FreeDIOPort(HAL_DigitalHandle dioPortHandle) { } int32_t status = 0; - std::lock_guard lock(digitalDIOMutex); + std::scoped_lock lock(digitalDIOMutex); if (port->channel >= kNumDigitalHeaders + kNumDigitalMXPChannels) { // Unset the SPI flag int32_t bitToUnset = 1 << remapSPIChannel(port->channel); @@ -205,7 +205,7 @@ void HAL_SetDigitalPWMDutyCycle(HAL_DigitalPWMHandle pwmGenerator, double rawDutyCycle = 256.0 * dutyCycle; if (rawDutyCycle > 255.5) rawDutyCycle = 255.5; { - std::lock_guard lock(digitalPwmMutex); + std::scoped_lock lock(digitalPwmMutex); uint16_t pwmPeriodPower = digitalSystem->readPWMPeriodPower(status); if (pwmPeriodPower < 4) { // The resolution of the duty cycle drops close to the highest @@ -251,7 +251,7 @@ void HAL_SetDIO(HAL_DigitalHandle dioPortHandle, HAL_Bool value, if (value != 0) value = 1; } { - std::lock_guard lock(digitalDIOMutex); + std::scoped_lock lock(digitalDIOMutex); tDIO::tDO currentDIO = digitalSystem->readDO(status); if (port->channel >= kNumDigitalHeaders + kNumDigitalMXPChannels) { @@ -289,7 +289,7 @@ void HAL_SetDIODirection(HAL_DigitalHandle dioPortHandle, HAL_Bool input, return; } { - std::lock_guard lock(digitalDIOMutex); + std::scoped_lock lock(digitalDIOMutex); tDIO::tOutputEnable currentDIO = digitalSystem->readOutputEnable(status); if (port->channel >= kNumDigitalHeaders + kNumDigitalMXPChannels) { @@ -421,7 +421,7 @@ void HAL_SetFilterSelect(HAL_DigitalHandle dioPortHandle, int32_t filterIndex, return; } - std::lock_guard lock(digitalDIOMutex); + std::scoped_lock lock(digitalDIOMutex); if (port->channel >= kNumDigitalHeaders + kNumDigitalMXPChannels) { // Channels 10-15 are SPI channels, so subtract our MXP channels digitalSystem->writeFilterSelectHdr(port->channel - kNumDigitalMXPChannels, @@ -441,7 +441,7 @@ int32_t HAL_GetFilterSelect(HAL_DigitalHandle dioPortHandle, int32_t* status) { return 0; } - std::lock_guard lock(digitalDIOMutex); + std::scoped_lock lock(digitalDIOMutex); if (port->channel >= kNumDigitalHeaders + kNumDigitalMXPChannels) { // Channels 10-15 are SPI channels, so subtract our MXP channels return digitalSystem->readFilterSelectHdr( @@ -457,7 +457,7 @@ int32_t HAL_GetFilterSelect(HAL_DigitalHandle dioPortHandle, int32_t* status) { void HAL_SetFilterPeriod(int32_t filterIndex, int64_t value, int32_t* status) { initializeDigital(status); if (*status != 0) return; - std::lock_guard lock(digitalDIOMutex); + std::scoped_lock lock(digitalDIOMutex); digitalSystem->writeFilterPeriodHdr(filterIndex, value, status); if (*status == 0) { digitalSystem->writeFilterPeriodMXP(filterIndex, value, status); @@ -470,7 +470,7 @@ int64_t HAL_GetFilterPeriod(int32_t filterIndex, int32_t* status) { uint32_t hdrPeriod = 0; uint32_t mxpPeriod = 0; { - std::lock_guard lock(digitalDIOMutex); + std::scoped_lock lock(digitalDIOMutex); hdrPeriod = digitalSystem->readFilterPeriodHdr(filterIndex, status); if (*status == 0) { mxpPeriod = digitalSystem->readFilterPeriodMXP(filterIndex, status); diff --git a/hal/src/main/native/athena/DigitalInternal.cpp b/hal/src/main/native/athena/DigitalInternal.cpp index c7707cdf5a..684d35ad1f 100644 --- a/hal/src/main/native/athena/DigitalInternal.cpp +++ b/hal/src/main/native/athena/DigitalInternal.cpp @@ -74,7 +74,7 @@ void initializeDigital(int32_t* status) { // Initial check, as if it's true initialization has finished if (initialized) return; - std::lock_guard lock(initializeMutex); + std::scoped_lock lock(initializeMutex); // Second check in case another thread was waiting if (initialized) return; diff --git a/hal/src/main/native/athena/FRCDriverStation.cpp b/hal/src/main/native/athena/FRCDriverStation.cpp index 7bdae14aef..a76287c7f5 100644 --- a/hal/src/main/native/athena/FRCDriverStation.cpp +++ b/hal/src/main/native/athena/FRCDriverStation.cpp @@ -180,7 +180,7 @@ static int32_t HAL_GetMatchInfoInternal(HAL_MatchInfo* info) { static void UpdateDriverStationControlWord(bool force, HAL_ControlWord& controlWord) { auto now = std::chrono::steady_clock::now(); - std::lock_guard lock(m_controlWordMutex); + std::scoped_lock lock(m_controlWordMutex); // Update every 50 ms or on force. if ((now - m_lastControlWordUpdate > std::chrono::milliseconds(50)) || force) { @@ -207,7 +207,7 @@ static void UpdateDriverStationDataCaches() { { // Obtain a lock on the data, swap the cached data into the main data arrays - std::lock_guard lock(m_cacheDataMutex); + std::scoped_lock lock(m_cacheDataMutex); m_joystickAxes.swap(m_joystickAxesCache); m_joystickPOVs.swap(m_joystickPOVsCache); @@ -272,7 +272,7 @@ int32_t HAL_SendError(HAL_Bool isError, int32_t errorCode, HAL_Bool isLVCode, // Avoid flooding console by keeping track of previous 5 error // messages and only printing again if they're longer than 1 second old. static constexpr int KEEP_MSGS = 5; - std::lock_guard lock(msgMutex); + std::scoped_lock lock(msgMutex); static std::string prevMsg[KEEP_MSGS]; static std::chrono::time_point prevMsgTime[KEEP_MSGS]; @@ -545,7 +545,7 @@ void HAL_InitializeDriverStation(void) { // Initial check, as if it's true initialization has finished if (initialized) return; - std::lock_guard lock(initializeMutex); + std::scoped_lock lock(initializeMutex); // Second check in case another thread was waiting if (initialized) return; diff --git a/hal/src/main/native/athena/HAL.cpp b/hal/src/main/native/athena/HAL.cpp index 0e55558204..0b1e5354f7 100644 --- a/hal/src/main/native/athena/HAL.cpp +++ b/hal/src/main/native/athena/HAL.cpp @@ -282,7 +282,7 @@ void HAL_BaseInitialize(int32_t* status) { // Initial check, as if it's true initialization has finished if (initialized) return; - std::lock_guard lock(initializeMutex); + std::scoped_lock lock(initializeMutex); // Second check in case another thread was waiting if (initialized) return; // image 4; Fixes errors caused by multiple processes. Talk to NI about this @@ -341,7 +341,7 @@ HAL_Bool HAL_Initialize(int32_t timeout, int32_t mode) { // Initial check, as if it's true initialization has finished if (initialized) return true; - std::lock_guard lock(initializeMutex); + std::scoped_lock lock(initializeMutex); // Second check in case another thread was waiting if (initialized) return true; diff --git a/hal/src/main/native/athena/I2C.cpp b/hal/src/main/native/athena/I2C.cpp index a6a0e185ab..b72e25eff1 100644 --- a/hal/src/main/native/athena/I2C.cpp +++ b/hal/src/main/native/athena/I2C.cpp @@ -52,7 +52,7 @@ void HAL_InitializeI2C(HAL_I2CPort port, int32_t* status) { } if (port == HAL_I2C_kOnboard) { - std::lock_guard lock(digitalI2COnBoardMutex); + std::scoped_lock lock(digitalI2COnBoardMutex); i2COnboardObjCount++; if (i2COnboardObjCount > 1) return; int handle = open("/dev/i2c-2", O_RDWR); @@ -62,7 +62,7 @@ void HAL_InitializeI2C(HAL_I2CPort port, int32_t* status) { } i2COnBoardHandle = handle; } else { - std::lock_guard lock(digitalI2CMXPMutex); + std::scoped_lock lock(digitalI2CMXPMutex); i2CMXPObjCount++; if (i2CMXPObjCount > 1) return; if ((i2CMXPDigitalHandle1 = HAL_InitializeDIOPort( @@ -108,10 +108,10 @@ int32_t HAL_TransactionI2C(HAL_I2CPort port, int32_t deviceAddress, rdwr.nmsgs = 2; if (port == HAL_I2C_kOnboard) { - std::lock_guard lock(digitalI2COnBoardMutex); + std::scoped_lock lock(digitalI2COnBoardMutex); return ioctl(i2COnBoardHandle, I2C_RDWR, &rdwr); } else { - std::lock_guard lock(digitalI2CMXPMutex); + std::scoped_lock lock(digitalI2CMXPMutex); return ioctl(i2CMXPHandle, I2C_RDWR, &rdwr); } } @@ -134,10 +134,10 @@ int32_t HAL_WriteI2C(HAL_I2CPort port, int32_t deviceAddress, rdwr.nmsgs = 1; if (port == HAL_I2C_kOnboard) { - std::lock_guard lock(digitalI2COnBoardMutex); + std::scoped_lock lock(digitalI2COnBoardMutex); return ioctl(i2COnBoardHandle, I2C_RDWR, &rdwr); } else { - std::lock_guard lock(digitalI2CMXPMutex); + std::scoped_lock lock(digitalI2CMXPMutex); return ioctl(i2CMXPHandle, I2C_RDWR, &rdwr); } } @@ -160,10 +160,10 @@ int32_t HAL_ReadI2C(HAL_I2CPort port, int32_t deviceAddress, uint8_t* buffer, rdwr.nmsgs = 1; if (port == HAL_I2C_kOnboard) { - std::lock_guard lock(digitalI2COnBoardMutex); + std::scoped_lock lock(digitalI2COnBoardMutex); return ioctl(i2COnBoardHandle, I2C_RDWR, &rdwr); } else { - std::lock_guard lock(digitalI2CMXPMutex); + std::scoped_lock lock(digitalI2CMXPMutex); return ioctl(i2CMXPHandle, I2C_RDWR, &rdwr); } } @@ -175,12 +175,12 @@ void HAL_CloseI2C(HAL_I2CPort port) { } if (port == HAL_I2C_kOnboard) { - std::lock_guard lock(digitalI2COnBoardMutex); + std::scoped_lock lock(digitalI2COnBoardMutex); if (i2COnboardObjCount-- == 0) { close(i2COnBoardHandle); } } else { - std::lock_guard lock(digitalI2CMXPMutex); + std::scoped_lock lock(digitalI2CMXPMutex); if (i2CMXPObjCount-- == 0) { close(i2CMXPHandle); } diff --git a/hal/src/main/native/athena/Notifier.cpp b/hal/src/main/native/athena/Notifier.cpp index e4db9dcad5..662b04e155 100644 --- a/hal/src/main/native/athena/Notifier.cpp +++ b/hal/src/main/native/athena/Notifier.cpp @@ -53,7 +53,7 @@ class NotifierHandleContainer ~NotifierHandleContainer() { ForEach([](HAL_NotifierHandle handle, Notifier* notifier) { { - std::lock_guard lock(notifier->mutex); + std::scoped_lock lock(notifier->mutex); notifier->triggerTime = UINT64_MAX; notifier->triggeredTime = 0; notifier->active = false; @@ -66,7 +66,7 @@ class NotifierHandleContainer static NotifierHandleContainer* notifierHandles; static void alarmCallback(uint32_t, void*) { - std::lock_guard lock(notifierMutex); + std::scoped_lock lock(notifierMutex); int32_t status = 0; uint64_t currentTime = 0; @@ -119,7 +119,7 @@ HAL_NotifierHandle HAL_InitializeNotifier(int32_t* status) { std::atexit(cleanupNotifierAtExit); if (notifierRefCount.fetch_add(1) == 0) { - std::lock_guard lock(notifierMutex); + std::scoped_lock lock(notifierMutex); // create manager and alarm if not already created if (!notifierManager) { notifierManager = std::make_unique( @@ -144,7 +144,7 @@ void HAL_StopNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) { if (!notifier) return; { - std::lock_guard lock(notifier->mutex); + std::scoped_lock lock(notifier->mutex); notifier->triggerTime = UINT64_MAX; notifier->triggeredTime = 0; notifier->active = false; @@ -158,7 +158,7 @@ void HAL_CleanNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) { // Just in case HAL_StopNotifier() wasn't called... { - std::lock_guard lock(notifier->mutex); + std::scoped_lock lock(notifier->mutex); notifier->triggerTime = UINT64_MAX; notifier->triggeredTime = 0; notifier->active = false; @@ -177,7 +177,7 @@ void HAL_CleanNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) { // if (notifierAlarm) notifierAlarm->writeEnable(false, status); // if (notifierManager) notifierManager->disable(status); - // std::lock_guard lock(notifierMutex); + // std::scoped_lock lock(notifierMutex); // notifierAlarm = nullptr; // notifierManager = nullptr; // closestTrigger = UINT64_MAX; @@ -190,12 +190,12 @@ void HAL_UpdateNotifierAlarm(HAL_NotifierHandle notifierHandle, if (!notifier) return; { - std::lock_guard lock(notifier->mutex); + std::scoped_lock lock(notifier->mutex); notifier->triggerTime = triggerTime; notifier->triggeredTime = UINT64_MAX; } - std::lock_guard lock(notifierMutex); + std::scoped_lock lock(notifierMutex); // Update alarm time if closer than current. if (triggerTime < closestTrigger) { bool wasActive = (closestTrigger != UINT64_MAX); @@ -214,7 +214,7 @@ void HAL_CancelNotifierAlarm(HAL_NotifierHandle notifierHandle, if (!notifier) return; { - std::lock_guard lock(notifier->mutex); + std::scoped_lock lock(notifier->mutex); notifier->triggerTime = UINT64_MAX; } } diff --git a/hal/src/main/native/athena/PDP.cpp b/hal/src/main/native/athena/PDP.cpp index 4d5c7ec2ab..b9daf413df 100644 --- a/hal/src/main/native/athena/PDP.cpp +++ b/hal/src/main/native/athena/PDP.cpp @@ -130,7 +130,7 @@ HAL_PDPHandle HAL_InitializePDP(int32_t module, int32_t* status) { return HAL_kInvalidHandle; } - std::lock_guard lock(pdpHandleMutex); + std::scoped_lock lock(pdpHandleMutex); if (pdpHandles[module] != HAL_kInvalidHandle) { *status = 0; diff --git a/hal/src/main/native/athena/Relay.cpp b/hal/src/main/native/athena/Relay.cpp index 634e5982df..71880a8d21 100644 --- a/hal/src/main/native/athena/Relay.cpp +++ b/hal/src/main/native/athena/Relay.cpp @@ -100,7 +100,7 @@ void HAL_SetRelay(HAL_RelayHandle relayPortHandle, HAL_Bool on, *status = HAL_HANDLE_ERROR; return; } - std::lock_guard lock(digitalRelayMutex); + std::scoped_lock lock(digitalRelayMutex); uint8_t relays = 0; if (port->fwd) { relays = relaySystem->readValue_Forward(status); diff --git a/hal/src/main/native/athena/SPI.cpp b/hal/src/main/native/athena/SPI.cpp index edeec7d634..bb0666a1a0 100644 --- a/hal/src/main/native/athena/SPI.cpp +++ b/hal/src/main/native/athena/SPI.cpp @@ -55,7 +55,7 @@ static bool SPIInUseByAuto(HAL_SPIPort port) { // There are two SPI devices: one for ports 0-3 (onboard), the other for port // 4 (MXP). if (!spiAutoRunning) return false; - std::lock_guard lock(spiAutoMutex); + std::scoped_lock lock(spiAutoMutex); return (spiAutoPort >= 0 && spiAutoPort <= 3 && port >= 0 && port <= 3) || (spiAutoPort == 4 && port == 4); } @@ -253,7 +253,7 @@ int32_t HAL_TransactionSPI(HAL_SPIPort port, const uint8_t* dataToSend, xfer.rx_buf = (__u64)dataReceived; xfer.len = size; - std::lock_guard lock(spiApiMutexes[port]); + std::scoped_lock lock(spiApiMutexes[port]); return ioctl(HAL_GetSPIHandle(port), SPI_IOC_MESSAGE(1), &xfer); } @@ -270,7 +270,7 @@ int32_t HAL_WriteSPI(HAL_SPIPort port, const uint8_t* dataToSend, xfer.tx_buf = (__u64)dataToSend; xfer.len = sendSize; - std::lock_guard lock(spiApiMutexes[port]); + std::scoped_lock lock(spiApiMutexes[port]); return ioctl(HAL_GetSPIHandle(port), SPI_IOC_MESSAGE(1), &xfer); } @@ -286,7 +286,7 @@ int32_t HAL_ReadSPI(HAL_SPIPort port, uint8_t* buffer, int32_t count) { xfer.rx_buf = (__u64)buffer; xfer.len = count; - std::lock_guard lock(spiApiMutexes[port]); + std::scoped_lock lock(spiApiMutexes[port]); return ioctl(HAL_GetSPIHandle(port), SPI_IOC_MESSAGE(1), &xfer); } @@ -299,7 +299,7 @@ void HAL_CloseSPI(HAL_SPIPort port) { HAL_FreeSPIAuto(port, &status); { - std::lock_guard lock(spiApiMutexes[port]); + std::scoped_lock lock(spiApiMutexes[port]); close(HAL_GetSPIHandle(port)); } @@ -335,7 +335,7 @@ void HAL_SetSPISpeed(HAL_SPIPort port, int32_t speed) { return; } - std::lock_guard lock(spiApiMutexes[port]); + std::scoped_lock lock(spiApiMutexes[port]); ioctl(HAL_GetSPIHandle(port), SPI_IOC_WR_MAX_SPEED_HZ, &speed); } @@ -350,7 +350,7 @@ void HAL_SetSPIOpts(HAL_SPIPort port, HAL_Bool msbFirst, mode |= (clkIdleHigh ? 2 : 0); mode |= (sampleOnTrailing ? 1 : 0); - std::lock_guard lock(spiApiMutexes[port]); + std::scoped_lock lock(spiApiMutexes[port]); ioctl(HAL_GetSPIHandle(port), SPI_IOC_WR_MODE, &mode); } @@ -360,7 +360,7 @@ void HAL_SetSPIChipSelectActiveHigh(HAL_SPIPort port, int32_t* status) { return; } - std::lock_guard lock(spiApiMutexes[port]); + std::scoped_lock lock(spiApiMutexes[port]); if (port < 4) { spiSystem->writeChipSelectActiveHigh_Hdr( spiSystem->readChipSelectActiveHigh_Hdr(status) | (1 << port), status); @@ -375,7 +375,7 @@ void HAL_SetSPIChipSelectActiveLow(HAL_SPIPort port, int32_t* status) { return; } - std::lock_guard lock(spiApiMutexes[port]); + std::scoped_lock lock(spiApiMutexes[port]); if (port < 4) { spiSystem->writeChipSelectActiveHigh_Hdr( spiSystem->readChipSelectActiveHigh_Hdr(status) & ~(1 << port), status); @@ -389,7 +389,7 @@ int32_t HAL_GetSPIHandle(HAL_SPIPort port) { return 0; } - std::lock_guard lock(spiHandleMutexes[port]); + std::scoped_lock lock(spiHandleMutexes[port]); switch (port) { case 0: return m_spiCS0Handle; @@ -411,7 +411,7 @@ void HAL_SetSPIHandle(HAL_SPIPort port, int32_t handle) { return; } - std::lock_guard lock(spiHandleMutexes[port]); + std::scoped_lock lock(spiHandleMutexes[port]); switch (port) { case 0: m_spiCS0Handle = handle; @@ -439,7 +439,7 @@ void HAL_InitSPIAuto(HAL_SPIPort port, int32_t bufferSize, int32_t* status) { return; } - std::lock_guard lock(spiAutoMutex); + std::scoped_lock lock(spiAutoMutex); // FPGA only has one auto SPI engine if (spiAutoPort != kSpiMaxHandles) { *status = RESOURCE_IS_ALLOCATED; @@ -470,7 +470,7 @@ void HAL_FreeSPIAuto(HAL_SPIPort port, int32_t* status) { return; } - std::lock_guard lock(spiAutoMutex); + std::scoped_lock lock(spiAutoMutex); if (spiAutoPort != port) return; spiAutoPort = kSpiMaxHandles; @@ -487,7 +487,7 @@ void HAL_FreeSPIAuto(HAL_SPIPort port, int32_t* status) { } void HAL_StartSPIAutoRate(HAL_SPIPort port, double period, int32_t* status) { - std::lock_guard lock(spiAutoMutex); + std::scoped_lock lock(spiAutoMutex); // FPGA only has one auto SPI engine if (port != spiAutoPort) { *status = INCOMPATIBLE_STATE; @@ -510,7 +510,7 @@ void HAL_StartSPIAutoTrigger(HAL_SPIPort port, HAL_Handle digitalSourceHandle, HAL_AnalogTriggerType analogTriggerType, HAL_Bool triggerRising, HAL_Bool triggerFalling, int32_t* status) { - std::lock_guard lock(spiAutoMutex); + std::scoped_lock lock(spiAutoMutex); // FPGA only has one auto SPI engine if (port != spiAutoPort) { *status = INCOMPATIBLE_STATE; @@ -545,7 +545,7 @@ void HAL_StartSPIAutoTrigger(HAL_SPIPort port, HAL_Handle digitalSourceHandle, } void HAL_StopSPIAuto(HAL_SPIPort port, int32_t* status) { - std::lock_guard lock(spiAutoMutex); + std::scoped_lock lock(spiAutoMutex); // FPGA only has one auto SPI engine if (port != spiAutoPort) { *status = INCOMPATIBLE_STATE; @@ -575,7 +575,7 @@ void HAL_SetSPIAutoTransmitData(HAL_SPIPort port, const uint8_t* dataToSend, return; } - std::lock_guard lock(spiAutoMutex); + std::scoped_lock lock(spiAutoMutex); // FPGA only has one auto SPI engine if (port != spiAutoPort) { *status = INCOMPATIBLE_STATE; @@ -594,7 +594,7 @@ void HAL_SetSPIAutoTransmitData(HAL_SPIPort port, const uint8_t* dataToSend, } void HAL_ForceSPIAutoRead(HAL_SPIPort port, int32_t* status) { - std::lock_guard lock(spiAutoMutex); + std::scoped_lock lock(spiAutoMutex); // FPGA only has one auto SPI engine if (port != spiAutoPort) { *status = INCOMPATIBLE_STATE; @@ -607,7 +607,7 @@ void HAL_ForceSPIAutoRead(HAL_SPIPort port, int32_t* status) { int32_t HAL_ReadSPIAutoReceivedData(HAL_SPIPort port, uint32_t* buffer, int32_t numToRead, double timeout, int32_t* status) { - std::lock_guard lock(spiAutoMutex); + std::scoped_lock lock(spiAutoMutex); // FPGA only has one auto SPI engine if (port != spiAutoPort) { *status = INCOMPATIBLE_STATE; @@ -621,7 +621,7 @@ int32_t HAL_ReadSPIAutoReceivedData(HAL_SPIPort port, uint32_t* buffer, } int32_t HAL_GetSPIAutoDroppedCount(HAL_SPIPort port, int32_t* status) { - std::lock_guard lock(spiAutoMutex); + std::scoped_lock lock(spiAutoMutex); // FPGA only has one auto SPI engine if (port != spiAutoPort) { *status = INCOMPATIBLE_STATE; diff --git a/hal/src/main/native/athena/cpp/SerialHelper.cpp b/hal/src/main/native/athena/cpp/SerialHelper.cpp index e610711c06..1f35e92d74 100644 --- a/hal/src/main/native/athena/cpp/SerialHelper.cpp +++ b/hal/src/main/native/athena/cpp/SerialHelper.cpp @@ -275,7 +275,7 @@ done: int32_t SerialHelper::GetIndexForPort(HAL_SerialPort port, int32_t* status) { // Hold lock whenever we're using the names array - std::lock_guard lock(m_nameMutex); + std::scoped_lock lock(m_nameMutex); std::string portString = m_usbNames[port - 2]; diff --git a/hal/src/main/native/athena/ctre/CtreCanNode.cpp b/hal/src/main/native/athena/ctre/CtreCanNode.cpp index 601ce4e97d..440bebdb98 100644 --- a/hal/src/main/native/athena/ctre/CtreCanNode.cpp +++ b/hal/src/main/native/athena/ctre/CtreCanNode.cpp @@ -86,7 +86,7 @@ CTR_Code CtreCanNode::GetRx(uint32_t arbId,uint8_t * dataBytes, uint32_t timeout if(timeoutMs > 999) timeoutMs = 999; FRC_NetworkCommunication_CANSessionMux_receiveMessage(&arbId,kFullMessageIDMask,dataBytes,&len,&timeStamp,&status); - std::lock_guard lock(_lck); + std::scoped_lock lock(_lck); if(status == 0){ /* fresh update */ rxEvent_t & r = _rxRxEvents[arbId]; /* lookup entry or make a default new one with all zeroes */ diff --git a/hal/src/main/native/cpp/handles/HandlesInternal.cpp b/hal/src/main/native/cpp/handles/HandlesInternal.cpp index c2956e18dc..5e66ce1296 100644 --- a/hal/src/main/native/cpp/handles/HandlesInternal.cpp +++ b/hal/src/main/native/cpp/handles/HandlesInternal.cpp @@ -17,7 +17,7 @@ static wpi::SmallVector* globalHandles = nullptr; static wpi::mutex globalHandleMutex; HandleBase::HandleBase() { static wpi::SmallVector gH; - std::lock_guard lock(globalHandleMutex); + std::scoped_lock lock(globalHandleMutex); if (!globalHandles) { globalHandles = &gH; } @@ -30,7 +30,7 @@ HandleBase::HandleBase() { } } HandleBase::~HandleBase() { - std::lock_guard lock(globalHandleMutex); + std::scoped_lock lock(globalHandleMutex); auto index = std::find(globalHandles->begin(), globalHandles->end(), this); if (index != globalHandles->end()) { *index = nullptr; diff --git a/hal/src/main/native/include/hal/cpp/UnsafeDIO.h b/hal/src/main/native/include/hal/cpp/UnsafeDIO.h index d087f28c46..dad5eb7143 100644 --- a/hal/src/main/native/include/hal/cpp/UnsafeDIO.h +++ b/hal/src/main/native/include/hal/cpp/UnsafeDIO.h @@ -77,7 +77,7 @@ void UnsafeManipulateDIO(HAL_DigitalHandle handle, int32_t* status, tDIO* dSys = detail::UnsafeGetDigialSystem(); auto mask = detail::ComputeDigitalMask(handle, status); if (status != 0) return; - std::lock_guard lock(dioMutex); + std::scoped_lock lock(dioMutex); tDIO::tOutputEnable enableOE = dSys->readOutputEnable(status); enableOE.value |= mask; diff --git a/hal/src/main/native/include/hal/handles/DigitalHandleResource.h b/hal/src/main/native/include/hal/handles/DigitalHandleResource.h index 39c1112fd6..dcd4b97caf 100644 --- a/hal/src/main/native/include/hal/handles/DigitalHandleResource.h +++ b/hal/src/main/native/include/hal/handles/DigitalHandleResource.h @@ -59,7 +59,7 @@ THandle DigitalHandleResource::Allocate( *status = RESOURCE_OUT_OF_RANGE; return HAL_kInvalidHandle; } - std::lock_guard lock(m_handleMutexes[index]); + std::scoped_lock lock(m_handleMutexes[index]); // check for allocation, otherwise allocate and return a valid handle if (m_structures[index] != nullptr) { *status = RESOURCE_IS_ALLOCATED; @@ -77,7 +77,7 @@ std::shared_ptr DigitalHandleResource::Get( if (index < 0 || index >= size) { return nullptr; } - std::lock_guard lock(m_handleMutexes[index]); + std::scoped_lock lock(m_handleMutexes[index]); // return structure. Null will propogate correctly, so no need to manually // check. return m_structures[index]; @@ -90,14 +90,14 @@ void DigitalHandleResource::Free( int16_t index = getHandleTypedIndex(handle, enumValue, m_version); if (index < 0 || index >= size) return; // lock and deallocated handle - std::lock_guard lock(m_handleMutexes[index]); + std::scoped_lock lock(m_handleMutexes[index]); m_structures[index].reset(); } template void DigitalHandleResource::ResetHandles() { for (int i = 0; i < size; i++) { - std::lock_guard lock(m_handleMutexes[i]); + std::scoped_lock lock(m_handleMutexes[i]); m_structures[i].reset(); } HandleBase::ResetHandles(); diff --git a/hal/src/main/native/include/hal/handles/IndexedClassedHandleResource.h b/hal/src/main/native/include/hal/handles/IndexedClassedHandleResource.h index fd7e51d122..2725573d41 100644 --- a/hal/src/main/native/include/hal/handles/IndexedClassedHandleResource.h +++ b/hal/src/main/native/include/hal/handles/IndexedClassedHandleResource.h @@ -66,7 +66,7 @@ IndexedClassedHandleResource::Allocate( *status = RESOURCE_OUT_OF_RANGE; return HAL_kInvalidHandle; } - std::lock_guard lock(m_handleMutexes[index]); + std::scoped_lock lock(m_handleMutexes[index]); // check for allocation, otherwise allocate and return a valid handle if (m_structures[index] != nullptr) { *status = RESOURCE_IS_ALLOCATED; @@ -86,7 +86,7 @@ IndexedClassedHandleResource::Get( if (index < 0 || index >= size) { return nullptr; } - std::lock_guard lock(m_handleMutexes[index]); + std::scoped_lock lock(m_handleMutexes[index]); // return structure. Null will propogate correctly, so no need to manually // check. return m_structures[index]; @@ -100,7 +100,7 @@ void IndexedClassedHandleResource::Free( int16_t index = getHandleTypedIndex(handle, enumValue, m_version); if (index < 0 || index >= size) return; // lock and deallocated handle - std::lock_guard lock(m_handleMutexes[index]); + std::scoped_lock lock(m_handleMutexes[index]); m_structures[index].reset(); } @@ -109,7 +109,7 @@ template ::ResetHandles() { for (int i = 0; i < size; i++) { - std::lock_guard lock(m_handleMutexes[i]); + std::scoped_lock lock(m_handleMutexes[i]); m_structures[i].reset(); } HandleBase::ResetHandles(); diff --git a/hal/src/main/native/include/hal/handles/IndexedHandleResource.h b/hal/src/main/native/include/hal/handles/IndexedHandleResource.h index 011d33ae69..2bca4ce8ae 100644 --- a/hal/src/main/native/include/hal/handles/IndexedHandleResource.h +++ b/hal/src/main/native/include/hal/handles/IndexedHandleResource.h @@ -61,7 +61,7 @@ THandle IndexedHandleResource::Allocate( *status = RESOURCE_OUT_OF_RANGE; return HAL_kInvalidHandle; } - std::lock_guard lock(m_handleMutexes[index]); + std::scoped_lock lock(m_handleMutexes[index]); // check for allocation, otherwise allocate and return a valid handle if (m_structures[index] != nullptr) { *status = RESOURCE_IS_ALLOCATED; @@ -80,7 +80,7 @@ IndexedHandleResource::Get(THandle handle) { if (index < 0 || index >= size) { return nullptr; } - std::lock_guard lock(m_handleMutexes[index]); + std::scoped_lock lock(m_handleMutexes[index]); // return structure. Null will propogate correctly, so no need to manually // check. return m_structures[index]; @@ -94,7 +94,7 @@ void IndexedHandleResource::Free( int16_t index = getHandleTypedIndex(handle, enumValue, m_version); if (index < 0 || index >= size) return; // lock and deallocated handle - std::lock_guard lock(m_handleMutexes[index]); + std::scoped_lock lock(m_handleMutexes[index]); m_structures[index].reset(); } @@ -102,7 +102,7 @@ template void IndexedHandleResource::ResetHandles() { for (int i = 0; i < size; i++) { - std::lock_guard lock(m_handleMutexes[i]); + std::scoped_lock lock(m_handleMutexes[i]); m_structures[i].reset(); } HandleBase::ResetHandles(); diff --git a/hal/src/main/native/include/hal/handles/LimitedClassedHandleResource.h b/hal/src/main/native/include/hal/handles/LimitedClassedHandleResource.h index 2ad2f302ed..a991fc349b 100644 --- a/hal/src/main/native/include/hal/handles/LimitedClassedHandleResource.h +++ b/hal/src/main/native/include/hal/handles/LimitedClassedHandleResource.h @@ -58,12 +58,12 @@ THandle LimitedClassedHandleResource::Allocate( std::shared_ptr toSet) { // globally lock to loop through indices - std::lock_guard lock(m_allocateMutex); + std::scoped_lock lock(m_allocateMutex); for (int16_t i = 0; i < size; i++) { if (m_structures[i] == nullptr) { // if a false index is found, grab its specific mutex // and allocate it. - std::lock_guard lock(m_handleMutexes[i]); + std::scoped_lock lock(m_handleMutexes[i]); m_structures[i] = toSet; return static_cast(createHandle(i, enumValue, m_version)); } @@ -81,7 +81,7 @@ LimitedClassedHandleResource::Get( if (index < 0 || index >= size) { return nullptr; } - std::lock_guard lock(m_handleMutexes[index]); + std::scoped_lock lock(m_handleMutexes[index]); // return structure. Null will propogate correctly, so no need to manually // check. return m_structures[index]; @@ -95,8 +95,8 @@ void LimitedClassedHandleResource::Free( int16_t index = getHandleTypedIndex(handle, enumValue, m_version); if (index < 0 || index >= size) return; // lock and deallocated handle - std::lock_guard allocateLock(m_allocateMutex); - std::lock_guard handleLock(m_handleMutexes[index]); + std::scoped_lock allocateLock(m_allocateMutex); + std::scoped_lock handleLock(m_handleMutexes[index]); m_structures[index].reset(); } @@ -105,9 +105,9 @@ template ::ResetHandles() { { - std::lock_guard allocateLock(m_allocateMutex); + std::scoped_lock allocateLock(m_allocateMutex); for (int i = 0; i < size; i++) { - std::lock_guard handleLock(m_handleMutexes[i]); + std::scoped_lock handleLock(m_handleMutexes[i]); m_structures[i].reset(); } } diff --git a/hal/src/main/native/include/hal/handles/LimitedHandleResource.h b/hal/src/main/native/include/hal/handles/LimitedHandleResource.h index 95f3c4b772..07566340ea 100644 --- a/hal/src/main/native/include/hal/handles/LimitedHandleResource.h +++ b/hal/src/main/native/include/hal/handles/LimitedHandleResource.h @@ -54,12 +54,12 @@ template THandle LimitedHandleResource::Allocate() { // globally lock to loop through indices - std::lock_guard lock(m_allocateMutex); + std::scoped_lock lock(m_allocateMutex); for (int16_t i = 0; i < size; i++) { if (m_structures[i] == nullptr) { // if a false index is found, grab its specific mutex // and allocate it. - std::lock_guard lock(m_handleMutexes[i]); + std::scoped_lock lock(m_handleMutexes[i]); m_structures[i] = std::make_shared(); return static_cast(createHandle(i, enumValue, m_version)); } @@ -76,7 +76,7 @@ LimitedHandleResource::Get(THandle handle) { if (index < 0 || index >= size) { return nullptr; } - std::lock_guard lock(m_handleMutexes[index]); + std::scoped_lock lock(m_handleMutexes[index]); // return structure. Null will propogate correctly, so no need to manually // check. return m_structures[index]; @@ -90,8 +90,8 @@ void LimitedHandleResource::Free( int16_t index = getHandleTypedIndex(handle, enumValue, m_version); if (index < 0 || index >= size) return; // lock and deallocated handle - std::lock_guard allocateLock(m_allocateMutex); - std::lock_guard handleLock(m_handleMutexes[index]); + std::scoped_lock allocateLock(m_allocateMutex); + std::scoped_lock handleLock(m_handleMutexes[index]); m_structures[index].reset(); } @@ -99,9 +99,9 @@ template void LimitedHandleResource::ResetHandles() { { - std::lock_guard allocateLock(m_allocateMutex); + std::scoped_lock allocateLock(m_allocateMutex); for (int i = 0; i < size; i++) { - std::lock_guard handleLock(m_handleMutexes[i]); + std::scoped_lock handleLock(m_handleMutexes[i]); m_structures[i].reset(); } } diff --git a/hal/src/main/native/include/hal/handles/UnlimitedHandleResource.h b/hal/src/main/native/include/hal/handles/UnlimitedHandleResource.h index 332c2de6ab..96a91f846c 100644 --- a/hal/src/main/native/include/hal/handles/UnlimitedHandleResource.h +++ b/hal/src/main/native/include/hal/handles/UnlimitedHandleResource.h @@ -63,7 +63,7 @@ class UnlimitedHandleResource : public HandleBase { template THandle UnlimitedHandleResource::Allocate( std::shared_ptr structure) { - std::lock_guard lock(m_handleMutex); + std::scoped_lock lock(m_handleMutex); size_t i; for (i = 0; i < m_structures.size(); i++) { if (m_structures[i] == nullptr) { @@ -82,7 +82,7 @@ template std::shared_ptr UnlimitedHandleResource::Get(THandle handle) { int16_t index = getHandleTypedIndex(handle, enumValue, m_version); - std::lock_guard lock(m_handleMutex); + std::scoped_lock lock(m_handleMutex); if (index < 0 || index >= static_cast(m_structures.size())) return nullptr; return m_structures[index]; @@ -92,7 +92,7 @@ template std::shared_ptr UnlimitedHandleResource::Free(THandle handle) { int16_t index = getHandleTypedIndex(handle, enumValue, m_version); - std::lock_guard lock(m_handleMutex); + std::scoped_lock lock(m_handleMutex); if (index < 0 || index >= static_cast(m_structures.size())) return nullptr; return std::move(m_structures[index]); @@ -101,7 +101,7 @@ UnlimitedHandleResource::Free(THandle handle) { template void UnlimitedHandleResource::ResetHandles() { { - std::lock_guard lock(m_handleMutex); + std::scoped_lock lock(m_handleMutex); for (size_t i = 0; i < m_structures.size(); i++) { m_structures[i].reset(); } @@ -113,7 +113,7 @@ template template void UnlimitedHandleResource::ForEach( Functor func) { - std::lock_guard lock(m_handleMutex); + std::scoped_lock lock(m_handleMutex); size_t i; for (i = 0; i < m_structures.size(); i++) { if (m_structures[i] != nullptr) { diff --git a/hal/src/main/native/include/mockdata/SimCallbackRegistry.h b/hal/src/main/native/include/mockdata/SimCallbackRegistry.h index 0ba7614a22..7190dcfdd5 100644 --- a/hal/src/main/native/include/mockdata/SimCallbackRegistry.h +++ b/hal/src/main/native/include/mockdata/SimCallbackRegistry.h @@ -29,12 +29,12 @@ class SimCallbackRegistryBase { public: void Cancel(int32_t uid) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (m_callbacks) m_callbacks->erase(uid - 1); } void Reset() { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); DoReset(); } @@ -68,13 +68,13 @@ template class SimCallbackRegistry : public impl::SimCallbackRegistryBase { public: int32_t Register(CallbackFunction callback, void* param) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); return DoRegister(reinterpret_cast(callback), param); } template void Invoke(U&&... u) const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (m_callbacks) { const char* name = GetName(); for (auto&& cb : *m_callbacks) diff --git a/hal/src/main/native/include/mockdata/SimDataValue.h b/hal/src/main/native/include/mockdata/SimDataValue.h index faa0c71073..b6723bbcb7 100644 --- a/hal/src/main/native/include/mockdata/SimDataValue.h +++ b/hal/src/main/native/include/mockdata/SimDataValue.h @@ -27,14 +27,14 @@ class SimDataValueBase : protected SimCallbackRegistryBase { LLVM_ATTRIBUTE_ALWAYS_INLINE void CancelCallback(int32_t uid) { Cancel(uid); } T Get() const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); return m_value; } LLVM_ATTRIBUTE_ALWAYS_INLINE operator T() const { return Get(); } void Reset(T value) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); DoReset(); m_value = value; } @@ -57,7 +57,7 @@ class SimDataValueBase : protected SimCallbackRegistryBase { } void DoSet(T value, const char* name) { - std::lock_guard lock(this->m_mutex); + std::scoped_lock lock(this->m_mutex); if (m_value != value) { m_value = value; if (m_callbacks) { diff --git a/hal/src/main/native/sim/CANAPI.cpp b/hal/src/main/native/sim/CANAPI.cpp index 1f6f40011d..76d5f1493d 100644 --- a/hal/src/main/native/sim/CANAPI.cpp +++ b/hal/src/main/native/sim/CANAPI.cpp @@ -100,7 +100,7 @@ HAL_CANHandle HAL_InitializeCAN(HAL_CANManufacturer manufacturer, void HAL_CleanCAN(HAL_CANHandle handle) { auto data = canHandles->Free(handle); - std::lock_guard lock(data->mapMutex); + std::scoped_lock lock(data->mapMutex); for (auto&& i : data->periodicSends) { int32_t s = 0; @@ -124,7 +124,7 @@ void HAL_WriteCANPacket(HAL_CANHandle handle, const uint8_t* data, if (*status != 0) { return; } - std::lock_guard lock(can->mapMutex); + std::scoped_lock lock(can->mapMutex); can->periodicSends[apiId] = -1; } @@ -143,7 +143,7 @@ void HAL_WriteCANPacketRepeating(HAL_CANHandle handle, const uint8_t* data, if (*status != 0) { return; } - std::lock_guard lock(can->mapMutex); + std::scoped_lock lock(can->mapMutex); can->periodicSends[apiId] = repeatMs; } @@ -162,7 +162,7 @@ void HAL_StopCANPacketRepeating(HAL_CANHandle handle, int32_t apiId, if (*status != 0) { return; } - std::lock_guard lock(can->mapMutex); + std::scoped_lock lock(can->mapMutex); can->periodicSends[apiId] = -1; } @@ -181,7 +181,7 @@ void HAL_ReadCANPacketNew(HAL_CANHandle handle, int32_t apiId, uint8_t* data, HAL_CAN_ReceiveMessage(&messageId, 0x1FFFFFFF, data, &dataSize, &ts, status); if (*status == 0) { - std::lock_guard lock(can->mapMutex); + std::scoped_lock lock(can->mapMutex); auto& msg = can->receives[messageId]; msg.length = dataSize; msg.lastTimeStamp = ts; @@ -206,7 +206,7 @@ void HAL_ReadCANPacketLatest(HAL_CANHandle handle, int32_t apiId, uint8_t* data, uint32_t ts = 0; HAL_CAN_ReceiveMessage(&messageId, 0x1FFFFFFF, data, &dataSize, &ts, status); - std::lock_guard lock(can->mapMutex); + std::scoped_lock lock(can->mapMutex); if (*status == 0) { // fresh update auto& msg = can->receives[messageId]; @@ -243,7 +243,7 @@ void HAL_ReadCANPacketTimeout(HAL_CANHandle handle, int32_t apiId, uint32_t ts = 0; HAL_CAN_ReceiveMessage(&messageId, 0x1FFFFFFF, data, &dataSize, &ts, status); - std::lock_guard lock(can->mapMutex); + std::scoped_lock lock(can->mapMutex); if (*status == 0) { // fresh update auto& msg = can->receives[messageId]; @@ -285,7 +285,7 @@ void HAL_ReadCANPeriodicPacket(HAL_CANHandle handle, int32_t apiId, uint32_t messageId = CreateCANId(can.get(), apiId); { - std::lock_guard lock(can->mapMutex); + std::scoped_lock lock(can->mapMutex); auto i = can->receives.find(messageId); if (i != can->receives.end()) { // Found, check if new enough @@ -305,7 +305,7 @@ void HAL_ReadCANPeriodicPacket(HAL_CANHandle handle, int32_t apiId, uint32_t ts = 0; HAL_CAN_ReceiveMessage(&messageId, 0x1FFFFFFF, data, &dataSize, &ts, status); - std::lock_guard lock(can->mapMutex); + std::scoped_lock lock(can->mapMutex); if (*status == 0) { // fresh update auto& msg = can->receives[messageId]; diff --git a/hal/src/main/native/sim/DriverStation.cpp b/hal/src/main/native/sim/DriverStation.cpp index 1eef4a741e..ddb1c0ef2b 100644 --- a/hal/src/main/native/sim/DriverStation.cpp +++ b/hal/src/main/native/sim/DriverStation.cpp @@ -51,7 +51,7 @@ int32_t HAL_SendError(HAL_Bool isError, int32_t errorCode, HAL_Bool isLVCode, // Avoid flooding console by keeping track of previous 5 error // messages and only printing again if they're longer than 1 second old. static constexpr int KEEP_MSGS = 5; - std::lock_guard lock(msgMutex); + std::scoped_lock lock(msgMutex); static std::string prevMsg[KEEP_MSGS]; static std::chrono::time_point prevMsgTime[KEEP_MSGS]; @@ -262,7 +262,7 @@ static int32_t newDataOccur(uint32_t refNum) { // Since we could get other values, require our specific handle // to signal our threads if (refNum != refNumber) return 0; - std::lock_guard lock(newDSDataAvailableMutex); + std::scoped_lock lock(newDSDataAvailableMutex); // Nofify all threads newDSDataAvailableCounter++; newDSDataAvailableCond->notify_all(); @@ -276,7 +276,7 @@ void HAL_InitializeDriverStation(void) { // Initial check, as if it's true initialization has finished if (initialized) return; - std::lock_guard lock(initializeMutex); + std::scoped_lock lock(initializeMutex); // Second check in case another thread was waiting if (initialized) return; diff --git a/hal/src/main/native/sim/HAL.cpp b/hal/src/main/native/sim/HAL.cpp index 407e9df050..b82560e2cd 100644 --- a/hal/src/main/native/sim/HAL.cpp +++ b/hal/src/main/native/sim/HAL.cpp @@ -231,7 +231,7 @@ HAL_Bool HAL_Initialize(int32_t timeout, int32_t mode) { // Initial check, as if it's true initialization has finished if (initialized) return true; - std::lock_guard lock(initializeMutex); + std::scoped_lock lock(initializeMutex); // Second check in case another thread was waiting if (initialized) return true; diff --git a/hal/src/main/native/sim/Notifier.cpp b/hal/src/main/native/sim/Notifier.cpp index a8de216d26..579540c2c6 100644 --- a/hal/src/main/native/sim/Notifier.cpp +++ b/hal/src/main/native/sim/Notifier.cpp @@ -38,7 +38,7 @@ class NotifierHandleContainer ~NotifierHandleContainer() { ForEach([](HAL_NotifierHandle handle, Notifier* notifier) { { - std::lock_guard lock(notifier->mutex); + std::scoped_lock lock(notifier->mutex); notifier->active = false; notifier->running = false; } @@ -76,7 +76,7 @@ void HAL_StopNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) { if (!notifier) return; { - std::lock_guard lock(notifier->mutex); + std::scoped_lock lock(notifier->mutex); notifier->active = false; notifier->running = false; } @@ -89,7 +89,7 @@ void HAL_CleanNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) { // Just in case HAL_StopNotifier() wasn't called... { - std::lock_guard lock(notifier->mutex); + std::scoped_lock lock(notifier->mutex); notifier->active = false; notifier->running = false; } @@ -102,7 +102,7 @@ void HAL_UpdateNotifierAlarm(HAL_NotifierHandle notifierHandle, if (!notifier) return; { - std::lock_guard lock(notifier->mutex); + std::scoped_lock lock(notifier->mutex); notifier->waitTime = triggerTime; notifier->running = true; notifier->updatedAlarm = true; @@ -118,7 +118,7 @@ void HAL_CancelNotifierAlarm(HAL_NotifierHandle notifierHandle, if (!notifier) return; { - std::lock_guard lock(notifier->mutex); + std::scoped_lock lock(notifier->mutex); notifier->running = false; } } diff --git a/hal/src/main/native/sim/mockdata/DriverStationData.cpp b/hal/src/main/native/sim/mockdata/DriverStationData.cpp index 72123ba3b5..ece98c8102 100644 --- a/hal/src/main/native/sim/mockdata/DriverStationData.cpp +++ b/hal/src/main/native/sim/mockdata/DriverStationData.cpp @@ -46,7 +46,7 @@ void DriverStationData::ResetData() { matchTime.Reset(0.0); { - std::lock_guard lock(m_joystickDataMutex); + std::scoped_lock lock(m_joystickDataMutex); m_joystickAxes = std::make_unique(6); m_joystickPOVs = std::make_unique(6); m_joystickButtons = std::make_unique(6); @@ -63,7 +63,7 @@ void DriverStationData::ResetData() { } } { - std::lock_guard lock(m_matchInfoMutex); + std::scoped_lock lock(m_matchInfoMutex); m_matchInfo = std::make_unique(); } @@ -71,22 +71,22 @@ void DriverStationData::ResetData() { void DriverStationData::GetJoystickAxes(int32_t joystickNum, HAL_JoystickAxes* axes) { - std::lock_guard lock(m_joystickDataMutex); + std::scoped_lock lock(m_joystickDataMutex); *axes = m_joystickAxes[joystickNum]; } void DriverStationData::GetJoystickPOVs(int32_t joystickNum, HAL_JoystickPOVs* povs) { - std::lock_guard lock(m_joystickDataMutex); + std::scoped_lock lock(m_joystickDataMutex); *povs = m_joystickPOVs[joystickNum]; } void DriverStationData::GetJoystickButtons(int32_t joystickNum, HAL_JoystickButtons* buttons) { - std::lock_guard lock(m_joystickDataMutex); + std::scoped_lock lock(m_joystickDataMutex); *buttons = m_joystickButtons[joystickNum]; } void DriverStationData::GetJoystickDescriptor( int32_t joystickNum, HAL_JoystickDescriptor* descriptor) { - std::lock_guard lock(m_joystickDataMutex); + std::scoped_lock lock(m_joystickDataMutex); *descriptor = m_joystickDescriptor[joystickNum]; // Always ensure name is null terminated descriptor->name[255] = '\0'; @@ -95,49 +95,49 @@ void DriverStationData::GetJoystickOutputs(int32_t joystickNum, int64_t* outputs, int32_t* leftRumble, int32_t* rightRumble) { - std::lock_guard lock(m_joystickDataMutex); + std::scoped_lock lock(m_joystickDataMutex); *leftRumble = m_joystickOutputs[joystickNum].leftRumble; *outputs = m_joystickOutputs[joystickNum].outputs; *rightRumble = m_joystickOutputs[joystickNum].rightRumble; } void DriverStationData::GetMatchInfo(HAL_MatchInfo* info) { - std::lock_guard lock(m_matchInfoMutex); + std::scoped_lock lock(m_matchInfoMutex); *info = *m_matchInfo; } void DriverStationData::SetJoystickAxes(int32_t joystickNum, const HAL_JoystickAxes* axes) { - std::lock_guard lock(m_joystickDataMutex); + std::scoped_lock lock(m_joystickDataMutex); m_joystickAxes[joystickNum] = *axes; } void DriverStationData::SetJoystickPOVs(int32_t joystickNum, const HAL_JoystickPOVs* povs) { - std::lock_guard lock(m_joystickDataMutex); + std::scoped_lock lock(m_joystickDataMutex); m_joystickPOVs[joystickNum] = *povs; } void DriverStationData::SetJoystickButtons(int32_t joystickNum, const HAL_JoystickButtons* buttons) { - std::lock_guard lock(m_joystickDataMutex); + std::scoped_lock lock(m_joystickDataMutex); m_joystickButtons[joystickNum] = *buttons; } void DriverStationData::SetJoystickDescriptor( int32_t joystickNum, const HAL_JoystickDescriptor* descriptor) { - std::lock_guard lock(m_joystickDataMutex); + std::scoped_lock lock(m_joystickDataMutex); m_joystickDescriptor[joystickNum] = *descriptor; } void DriverStationData::SetJoystickOutputs(int32_t joystickNum, int64_t outputs, int32_t leftRumble, int32_t rightRumble) { - std::lock_guard lock(m_joystickDataMutex); + std::scoped_lock lock(m_joystickDataMutex); m_joystickOutputs[joystickNum].leftRumble = leftRumble; m_joystickOutputs[joystickNum].outputs = outputs; m_joystickOutputs[joystickNum].rightRumble = rightRumble; } void DriverStationData::SetMatchInfo(const HAL_MatchInfo* info) { - std::lock_guard lock(m_matchInfoMutex); + std::scoped_lock lock(m_matchInfoMutex); *m_matchInfo = *info; *(std::end(m_matchInfo->eventName) - 1) = '\0'; } diff --git a/ntcore/src/main/native/cpp/CallbackManager.h b/ntcore/src/main/native/cpp/CallbackManager.h index 530bfd6993..2d9b11dbb8 100644 --- a/ntcore/src/main/native/cpp/CallbackManager.h +++ b/ntcore/src/main/native/cpp/CallbackManager.h @@ -74,7 +74,7 @@ class CallbackThread : public wpi::SafeThread { struct Poller { void Terminate() { { - std::lock_guard lock(poll_mutex); + std::scoped_lock lock(poll_mutex); terminating = true; } poll_cond.notify_all(); @@ -94,7 +94,7 @@ class CallbackThread : public wpi::SafeThread { auto poller = m_pollers[poller_uid]; if (!poller) return; { - std::lock_guard lock(poller->poll_mutex); + std::scoped_lock lock(poller->poll_mutex); poller->poll_queue.emplace(std::forward(args)...); } poller->poll_cond.notify_one(); @@ -286,7 +286,7 @@ class CallbackManager { } { - std::lock_guard lock(poller->poll_mutex); + std::scoped_lock lock(poller->poll_mutex); poller->cancelling = true; } poller->poll_cond.notify_one(); diff --git a/ntcore/src/main/native/cpp/Dispatcher.cpp b/ntcore/src/main/native/cpp/Dispatcher.cpp index d4f33fd6cd..e07972202a 100644 --- a/ntcore/src/main/native/cpp/Dispatcher.cpp +++ b/ntcore/src/main/native/cpp/Dispatcher.cpp @@ -119,7 +119,7 @@ void DispatcherBase::StartServer( const Twine& persist_filename, std::unique_ptr acceptor) { { - std::lock_guard lock(m_user_mutex); + std::scoped_lock lock(m_user_mutex); if (m_active) return; m_active = true; } @@ -151,7 +151,7 @@ void DispatcherBase::StartServer( void DispatcherBase::StartClient() { { - std::lock_guard lock(m_user_mutex); + std::scoped_lock lock(m_user_mutex); if (m_active) return; m_active = true; } @@ -170,7 +170,7 @@ void DispatcherBase::Stop() { // wake up client thread with a reconnect { - std::lock_guard lock(m_user_mutex); + std::scoped_lock lock(m_user_mutex); m_client_connector = nullptr; } ClientReconnect(); @@ -184,7 +184,7 @@ void DispatcherBase::Stop() { std::vector> conns; { - std::lock_guard lock(m_user_mutex); + std::scoped_lock lock(m_user_mutex); conns.swap(m_connections); } @@ -202,14 +202,14 @@ void DispatcherBase::SetUpdateRate(double interval) { } void DispatcherBase::SetIdentity(const Twine& name) { - std::lock_guard lock(m_user_mutex); + std::scoped_lock lock(m_user_mutex); m_identity = name.str(); } void DispatcherBase::Flush() { auto now = std::chrono::steady_clock::now(); { - std::lock_guard lock(m_flush_mutex); + std::scoped_lock lock(m_flush_mutex); // don't allow flushes more often than every 10 ms if ((now - m_last_flush) < std::chrono::milliseconds(10)) return; m_last_flush = now; @@ -222,7 +222,7 @@ std::vector DispatcherBase::GetConnections() const { std::vector conns; if (!m_active) return conns; - std::lock_guard lock(m_user_mutex); + std::scoped_lock lock(m_user_mutex); for (auto& conn : m_connections) { if (conn->state() != NetworkConnection::kActive) continue; conns.emplace_back(conn->info()); @@ -234,7 +234,7 @@ std::vector DispatcherBase::GetConnections() const { bool DispatcherBase::IsConnected() const { if (!m_active) return false; - std::lock_guard lock(m_user_mutex); + std::scoped_lock lock(m_user_mutex); for (auto& conn : m_connections) { if (conn->state() == NetworkConnection::kActive) return true; } @@ -245,7 +245,7 @@ bool DispatcherBase::IsConnected() const { unsigned int DispatcherBase::AddListener( std::function callback, bool immediate_notify) const { - std::lock_guard lock(m_user_mutex); + std::scoped_lock lock(m_user_mutex); unsigned int uid = m_notifier.Add(callback); // perform immediate notifications if (immediate_notify) { @@ -259,7 +259,7 @@ unsigned int DispatcherBase::AddListener( unsigned int DispatcherBase::AddPolledListener(unsigned int poller_uid, bool immediate_notify) const { - std::lock_guard lock(m_user_mutex); + std::scoped_lock lock(m_user_mutex); unsigned int uid = m_notifier.AddPolled(poller_uid); // perform immediate notifications if (immediate_notify) { @@ -272,17 +272,17 @@ unsigned int DispatcherBase::AddPolledListener(unsigned int poller_uid, } void DispatcherBase::SetConnector(Connector connector) { - std::lock_guard lock(m_user_mutex); + std::scoped_lock lock(m_user_mutex); m_client_connector = std::move(connector); } void DispatcherBase::SetConnectorOverride(Connector connector) { - std::lock_guard lock(m_user_mutex); + std::scoped_lock lock(m_user_mutex); m_client_connector_override = std::move(connector); } void DispatcherBase::ClearConnectorOverride() { - std::lock_guard lock(m_user_mutex); + std::scoped_lock lock(m_user_mutex); m_client_connector_override = nullptr; } @@ -319,7 +319,7 @@ void DispatcherBase::DispatchThreadMain() { } { - std::lock_guard user_lock(m_user_mutex); + std::scoped_lock user_lock(m_user_mutex); bool reconnect = false; if (++count > 10) { @@ -350,7 +350,7 @@ void DispatcherBase::DispatchThreadMain() { void DispatcherBase::QueueOutgoing(std::shared_ptr msg, INetworkConnection* only, INetworkConnection* except) { - std::lock_guard user_lock(m_user_mutex); + std::scoped_lock user_lock(m_user_mutex); for (auto& conn : m_connections) { if (conn.get() == except) continue; if (only && conn.get() != only) continue; @@ -392,7 +392,7 @@ void DispatcherBase::ServerThreadMain() { std::bind(&IStorage::ProcessIncoming, &m_storage, _1, _2, std::weak_ptr(conn))); { - std::lock_guard lock(m_user_mutex); + std::scoped_lock lock(m_user_mutex); // reuse dead connection slots bool placed = false; for (auto& c : m_connections) { @@ -417,7 +417,7 @@ void DispatcherBase::ClientThreadMain() { // get next server to connect to { - std::lock_guard lock(m_user_mutex); + std::scoped_lock lock(m_user_mutex); if (m_client_connector_override) { connect = m_client_connector_override; } else { @@ -469,7 +469,7 @@ bool DispatcherBase::ClientHandshake( // get identity std::string self_id; { - std::lock_guard lock(m_user_mutex); + std::scoped_lock lock(m_user_mutex); self_id = m_identity; } @@ -576,7 +576,7 @@ bool DispatcherBase::ServerHandshake( // Start with server hello. TODO: initial connection flag if (proto_rev >= 0x0300) { - std::lock_guard lock(m_user_mutex); + std::scoped_lock lock(m_user_mutex); outgoing.emplace_back(Message::ServerHello(0u, m_identity)); } @@ -633,7 +633,7 @@ bool DispatcherBase::ServerHandshake( void DispatcherBase::ClientReconnect(unsigned int proto_rev) { if ((m_networkMode & NT_NET_MODE_SERVER) != 0) return; { - std::lock_guard lock(m_user_mutex); + std::scoped_lock lock(m_user_mutex); m_reconnect_proto_rev = proto_rev; m_do_reconnect = true; } diff --git a/ntcore/src/main/native/cpp/InstanceImpl.cpp b/ntcore/src/main/native/cpp/InstanceImpl.cpp index 04bac20c29..cd35fb086f 100644 --- a/ntcore/src/main/native/cpp/InstanceImpl.cpp +++ b/ntcore/src/main/native/cpp/InstanceImpl.cpp @@ -43,7 +43,7 @@ InstanceImpl* InstanceImpl::Get(int inst) { } // slow path - std::lock_guard lock(s_mutex); + std::scoped_lock lock(s_mutex); // static fast-path block if (static_cast(inst) < @@ -66,7 +66,7 @@ int InstanceImpl::GetDefaultIndex() { if (inst >= 0) return inst; // slow path - std::lock_guard lock(s_mutex); + std::scoped_lock lock(s_mutex); // double-check inst = s_default; @@ -79,7 +79,7 @@ int InstanceImpl::GetDefaultIndex() { } int InstanceImpl::Alloc() { - std::lock_guard lock(s_mutex); + std::scoped_lock lock(s_mutex); return AllocImpl(); } @@ -96,7 +96,7 @@ int InstanceImpl::AllocImpl() { } void InstanceImpl::Destroy(int inst) { - std::lock_guard lock(s_mutex); + std::scoped_lock lock(s_mutex); if (inst < 0 || static_cast(inst) >= s_instances.size()) return; if (static_cast(inst) < diff --git a/ntcore/src/main/native/cpp/NetworkConnection.cpp b/ntcore/src/main/native/cpp/NetworkConnection.cpp index fd020b62ae..cb1e725a35 100644 --- a/ntcore/src/main/native/cpp/NetworkConnection.cpp +++ b/ntcore/src/main/native/cpp/NetworkConnection.cpp @@ -49,7 +49,7 @@ void NetworkConnection::Start() { while (!m_outgoing.empty()) m_outgoing.pop(); // reset shutdown flags { - std::lock_guard lock(m_shutdown_mutex); + std::scoped_lock lock(m_shutdown_mutex); m_read_shutdown = false; m_write_shutdown = false; } @@ -104,12 +104,12 @@ void NetworkConnection::set_proto_rev(unsigned int proto_rev) { } NetworkConnection::State NetworkConnection::state() const { - std::lock_guard lock(m_state_mutex); + std::scoped_lock lock(m_state_mutex); return m_state; } void NetworkConnection::set_state(State state) { - std::lock_guard lock(m_state_mutex); + std::scoped_lock lock(m_state_mutex); // Don't update state any more once we've died if (m_state == kDead) return; // One-shot notify state changes @@ -121,12 +121,12 @@ void NetworkConnection::set_state(State state) { } std::string NetworkConnection::remote_id() const { - std::lock_guard lock(m_remote_id_mutex); + std::scoped_lock lock(m_remote_id_mutex); return m_remote_id; } void NetworkConnection::set_remote_id(StringRef remote_id) { - std::lock_guard lock(m_remote_id_mutex); + std::scoped_lock lock(m_remote_id_mutex); m_remote_id = remote_id; } @@ -177,7 +177,7 @@ void NetworkConnection::ReadThreadMain() { done: // use condition variable to signal thread shutdown { - std::lock_guard lock(m_shutdown_mutex); + std::scoped_lock lock(m_shutdown_mutex); m_read_shutdown = true; m_read_shutdown_cv.notify_one(); } @@ -214,14 +214,14 @@ void NetworkConnection::WriteThreadMain() { // use condition variable to signal thread shutdown { - std::lock_guard lock(m_shutdown_mutex); + std::scoped_lock lock(m_shutdown_mutex); m_write_shutdown = true; m_write_shutdown_cv.notify_one(); } } void NetworkConnection::QueueOutgoing(std::shared_ptr msg) { - std::lock_guard lock(m_pending_mutex); + std::scoped_lock lock(m_pending_mutex); // Merge with previous. One case we don't combine: delete/assign loop. switch (msg->type()) { @@ -317,7 +317,7 @@ void NetworkConnection::QueueOutgoing(std::shared_ptr msg) { } void NetworkConnection::PostOutgoing(bool keep_alive) { - std::lock_guard lock(m_pending_mutex); + std::scoped_lock lock(m_pending_mutex); auto now = std::chrono::steady_clock::now(); if (m_pending_outgoing.empty()) { if (!keep_alive) return; diff --git a/ntcore/src/main/native/cpp/RpcServer.h b/ntcore/src/main/native/cpp/RpcServer.h index a8d4f2bedc..cca490f37b 100644 --- a/ntcore/src/main/native/cpp/RpcServer.h +++ b/ntcore/src/main/native/cpp/RpcServer.h @@ -64,7 +64,7 @@ class RpcServerThread RpcIdPair lookup_uid{local_id, call_uid}; callback(data); { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); auto i = m_response_map.find(lookup_uid); if (i != m_response_map.end()) { // post an empty response and erase it diff --git a/ntcore/src/main/native/cpp/Storage.cpp b/ntcore/src/main/native/cpp/Storage.cpp index a9b6eed554..611d455a04 100644 --- a/ntcore/src/main/native/cpp/Storage.cpp +++ b/ntcore/src/main/native/cpp/Storage.cpp @@ -30,7 +30,7 @@ Storage::~Storage() { } void Storage::SetDispatcher(IDispatcher* dispatcher, bool server) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_dispatcher = dispatcher; m_server = server; } @@ -38,7 +38,7 @@ void Storage::SetDispatcher(IDispatcher* dispatcher, bool server) { void Storage::ClearDispatcher() { m_dispatcher = nullptr; } NT_Type Storage::GetMessageEntryType(unsigned int id) const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (id >= m_idmap.size()) return NT_UNASSIGNED; Entry* entry = m_idmap[id]; if (!entry || !entry->value) return NT_UNASSIGNED; @@ -374,7 +374,7 @@ void Storage::ProcessIncomingRpcResponse(std::shared_ptr msg, void Storage::GetInitialAssignments( INetworkConnection& conn, std::vector>* msgs) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); conn.set_state(INetworkConnection::kSynchronized); for (auto& i : m_entries) { Entry* entry = i.getValue(); @@ -476,14 +476,14 @@ void Storage::ApplyInitialAssignments( } std::shared_ptr Storage::GetEntryValue(StringRef name) const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); auto i = m_entries.find(name); if (i == m_entries.end()) return nullptr; return i->getValue()->value; } std::shared_ptr Storage::GetEntryValue(unsigned int local_id) const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (local_id >= m_localmap.size()) return nullptr; return m_localmap[local_id]->value; } @@ -654,14 +654,14 @@ void Storage::SetEntryFlagsImpl(Entry* entry, unsigned int flags, } unsigned int Storage::GetEntryFlags(StringRef name) const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); auto i = m_entries.find(name); if (i == m_entries.end()) return 0; return i->getValue()->flags; } unsigned int Storage::GetEntryFlags(unsigned int local_id) const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (local_id >= m_localmap.size()) return 0; return m_localmap[local_id]->flags; } @@ -781,7 +781,7 @@ std::vector Storage::GetEntries(const Twine& prefix, unsigned int types) { wpi::SmallString<128> prefixBuf; StringRef prefixStr = prefix.toStringRef(prefixBuf); - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); std::vector ids; for (auto& i : m_entries) { Entry* entry = i.getValue(); @@ -839,7 +839,7 @@ std::vector Storage::GetEntryInfo(int inst, const Twine& prefix, unsigned int types) { wpi::SmallString<128> prefixBuf; StringRef prefixStr = prefix.toStringRef(prefixBuf); - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); std::vector infos; for (auto& i : m_entries) { Entry* entry = i.getValue(); @@ -863,7 +863,7 @@ unsigned int Storage::AddListener( unsigned int flags) const { wpi::SmallString<128> prefixBuf; StringRef prefixStr = prefix.toStringRef(prefixBuf); - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); unsigned int uid = m_notifier.Add(callback, prefixStr, flags); // perform immediate notifications if ((flags & NT_NOTIFY_IMMEDIATE) != 0 && (flags & NT_NOTIFY_NEW) != 0) { @@ -881,7 +881,7 @@ unsigned int Storage::AddListener( unsigned int local_id, std::function callback, unsigned int flags) const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); unsigned int uid = m_notifier.Add(callback, local_id, flags); // perform immediate notifications if ((flags & NT_NOTIFY_IMMEDIATE) != 0 && (flags & NT_NOTIFY_NEW) != 0 && @@ -900,7 +900,7 @@ unsigned int Storage::AddPolledListener(unsigned int poller, unsigned int flags) const { wpi::SmallString<128> prefixBuf; StringRef prefixStr = prefix.toStringRef(prefixBuf); - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); unsigned int uid = m_notifier.AddPolled(poller, prefixStr, flags); // perform immediate notifications if ((flags & NT_NOTIFY_IMMEDIATE) != 0 && (flags & NT_NOTIFY_NEW) != 0) { @@ -918,7 +918,7 @@ unsigned int Storage::AddPolledListener(unsigned int poller, unsigned int Storage::AddPolledListener(unsigned int poller, unsigned int local_id, unsigned int flags) const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); unsigned int uid = m_notifier.AddPolled(poller, local_id, flags); // perform immediate notifications if ((flags & NT_NOTIFY_IMMEDIATE) != 0 && (flags & NT_NOTIFY_NEW) != 0 && @@ -939,7 +939,7 @@ bool Storage::GetPersistentEntries( const { // copy values out of storage as quickly as possible so lock isn't held { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); // for periodic, don't re-save unless something has changed if (periodic && !m_persistent_dirty) return false; m_persistent_dirty = false; @@ -969,7 +969,7 @@ bool Storage::GetEntries( StringRef prefixStr = prefix.toStringRef(prefixBuf); // copy values out of storage as quickly as possible so lock isn't held { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); entries->reserve(m_entries.size()); for (auto& i : m_entries) { Entry* entry = i.getValue(); @@ -1055,7 +1055,7 @@ unsigned int Storage::CallRpc(unsigned int local_id, StringRef params) { unsigned int call_uid = msg->seq_num_uid(); m_rpc_server.ProcessRpc(local_id, call_uid, name, msg->str(), conn_info, [=](StringRef result) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_rpc_results.insert(std::make_pair( RpcIdPair{local_id, call_uid}, result)); m_rpc_results_cond.notify_all(); diff --git a/ntcore/src/main/native/cpp/networktables/NetworkTable.cpp b/ntcore/src/main/native/cpp/networktables/NetworkTable.cpp index 9fa6b770e9..6d4197697e 100644 --- a/ntcore/src/main/native/cpp/networktables/NetworkTable.cpp +++ b/ntcore/src/main/native/cpp/networktables/NetworkTable.cpp @@ -206,7 +206,7 @@ NetworkTableInstance NetworkTable::GetInstance() const { NetworkTableEntry NetworkTable::GetEntry(const Twine& key) const { wpi::SmallString<128> keyBuf; StringRef keyStr = key.toStringRef(keyBuf); - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); NT_Entry& entry = m_entries[keyStr]; if (entry == 0) { entry = nt::GetEntry(m_inst, m_path + Twine(PATH_SEPARATOR_CHAR) + keyStr); @@ -259,7 +259,7 @@ void NetworkTable::AddTableListener(ITableListener* listener, void NetworkTable::AddTableListenerEx(ITableListener* listener, unsigned int flags) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); wpi::SmallString<128> path(m_path); path += PATH_SEPARATOR_CHAR; size_t prefix_len = path.size(); @@ -283,7 +283,7 @@ void NetworkTable::AddTableListener(StringRef key, ITableListener* listener, void NetworkTable::AddTableListenerEx(StringRef key, ITableListener* listener, unsigned int flags) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); size_t prefix_len = m_path.size() + 1; auto entry = GetEntry(key); NT_EntryListener id = nt::AddEntryListener( @@ -336,7 +336,7 @@ void NetworkTable::RemoveTableListener(NT_EntryListener listener) { void NetworkTable::AddSubTableListener(ITableListener* listener, bool localNotify) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); size_t prefix_len = m_path.size() + 1; // The lambda needs to be copyable, but StringMap is not, so use @@ -362,7 +362,7 @@ void NetworkTable::AddSubTableListener(ITableListener* listener, } void NetworkTable::RemoveTableListener(ITableListener* listener) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); auto matches_begin = std::remove_if(m_listeners.begin(), m_listeners.end(), [=](const Listener& x) { return x.first == listener; }); @@ -397,7 +397,7 @@ std::vector NetworkTable::GetKeys(int types) const { std::vector keys; size_t prefix_len = m_path.size() + 1; auto infos = GetEntryInfo(m_inst, m_path + Twine(PATH_SEPARATOR_CHAR), types); - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); for (auto& info : infos) { auto relative_key = StringRef(info.name).substr(prefix_len); if (relative_key.find(PATH_SEPARATOR_CHAR) != StringRef::npos) continue; diff --git a/ntcore/src/main/native/cpp/ntcore_cpp.cpp b/ntcore/src/main/native/cpp/ntcore_cpp.cpp index aab83f0549..5a2b8afadb 100644 --- a/ntcore/src/main/native/cpp/ntcore_cpp.cpp +++ b/ntcore/src/main/native/cpp/ntcore_cpp.cpp @@ -959,7 +959,7 @@ void SetLogger(LogFunc func, unsigned int min_level) { auto ii = InstanceImpl::GetDefault(); static wpi::mutex mutex; static unsigned int logger = 0; - std::lock_guard lock(mutex); + std::scoped_lock lock(mutex); if (logger != 0) ii->logger_impl.Remove(logger); logger = ii->logger_impl.Add( [=](const LogMessage& msg) { diff --git a/simulation/halsim_adx_gyro_accelerometer/src/main/native/cpp/ADXRS450_SpiGyroWrapperData.cpp b/simulation/halsim_adx_gyro_accelerometer/src/main/native/cpp/ADXRS450_SpiGyroWrapperData.cpp index 932b738a7b..dc969be174 100644 --- a/simulation/halsim_adx_gyro_accelerometer/src/main/native/cpp/ADXRS450_SpiGyroWrapperData.cpp +++ b/simulation/halsim_adx_gyro_accelerometer/src/main/native/cpp/ADXRS450_SpiGyroWrapperData.cpp @@ -65,7 +65,7 @@ bool ADXRS450_SpiGyroWrapper::GetInitialized() const { } void ADXRS450_SpiGyroWrapper::ResetData() { - std::lock_guard lock(m_angle.GetMutex()); + std::scoped_lock lock(m_angle.GetMutex()); m_angle.Reset(0.0); m_angleDiff = 0; } @@ -78,7 +78,7 @@ void ADXRS450_SpiGyroWrapper::HandleRead(uint8_t* buffer, uint32_t count) { void ADXRS450_SpiGyroWrapper::HandleAutoReceiveData(uint32_t* buffer, int32_t numToRead, int32_t& outputCount) { - std::lock_guard lock(m_angle.GetMutex()); + std::scoped_lock lock(m_angle.GetMutex()); int32_t messagesToSend = 1 + std::abs(m_angleDiff > 0 ? std::ceil(m_angleDiff / kMaxAngleDeltaPerMessage) @@ -124,7 +124,7 @@ void ADXRS450_SpiGyroWrapper::HandleAutoReceiveData(uint32_t* buffer, } void ADXRS450_SpiGyroWrapper::SetAngle(double angle) { - std::lock_guard lock(m_angle.GetMutex()); + std::scoped_lock lock(m_angle.GetMutex()); if (m_angle != angle) { m_angleDiff += angle - m_angle; m_angle = angle; diff --git a/simulation/halsim_ds_nt/src/main/native/cpp/HALSimDsNt.cpp b/simulation/halsim_ds_nt/src/main/native/cpp/HALSimDsNt.cpp index d384091a56..d694530906 100644 --- a/simulation/halsim_ds_nt/src/main/native/cpp/HALSimDsNt.cpp +++ b/simulation/halsim_ds_nt/src/main/native/cpp/HALSimDsNt.cpp @@ -67,7 +67,7 @@ void HALSimDSNT::Initialize() { enabled.AddListener( [this](const nt::EntryNotification& ev) -> void { - std::lock_guard lock(modeMutex); + std::scoped_lock lock(modeMutex); if (!this->isEstop) { this->isEnabled = ev.value->GetBoolean(); } else { @@ -80,7 +80,7 @@ void HALSimDSNT::Initialize() { estop.AddListener( [this](const nt::EntryNotification& ev) -> void { - std::lock_guard lock(modeMutex); + std::scoped_lock lock(modeMutex); this->isEstop = ev.value->GetBoolean(); if (this->isEstop) { this->isEnabled = false; @@ -136,7 +136,7 @@ void HALSimDSNT::Initialize() { void HALSimDSNT::HandleModePress(enum HALSimDSNT_Mode mode, bool isPressed) { if (isPressed) { if (mode != currentMode) { - std::lock_guard lock(modeMutex); + std::scoped_lock lock(modeMutex); currentMode = mode; isEnabled = false; this->DoModeUpdate(); diff --git a/wpilibc/src/main/native/cpp/DigitalGlitchFilter.cpp b/wpilibc/src/main/native/cpp/DigitalGlitchFilter.cpp index 96b6b68484..811fab24d9 100644 --- a/wpilibc/src/main/native/cpp/DigitalGlitchFilter.cpp +++ b/wpilibc/src/main/native/cpp/DigitalGlitchFilter.cpp @@ -28,7 +28,7 @@ std::array DigitalGlitchFilter::m_filterAllocated = { wpi::mutex DigitalGlitchFilter::m_mutex; DigitalGlitchFilter::DigitalGlitchFilter() { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); auto index = std::find(m_filterAllocated.begin(), m_filterAllocated.end(), false); wpi_assert(index != m_filterAllocated.end()); @@ -43,7 +43,7 @@ DigitalGlitchFilter::DigitalGlitchFilter() { DigitalGlitchFilter::~DigitalGlitchFilter() { if (m_channelIndex >= 0) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_filterAllocated[m_channelIndex] = false; } } diff --git a/wpilibc/src/main/native/cpp/DriverStation.cpp b/wpilibc/src/main/native/cpp/DriverStation.cpp index 34e347fb04..a31473062c 100644 --- a/wpilibc/src/main/native/cpp/DriverStation.cpp +++ b/wpilibc/src/main/native/cpp/DriverStation.cpp @@ -490,7 +490,7 @@ void DriverStation::GetData() { } { - std::lock_guard waitLock(m_waitForDataMutex); + std::scoped_lock waitLock(m_waitForDataMutex); // Nofify all threads m_waitForDataCounter++; m_waitForDataCond.notify_all(); diff --git a/wpilibc/src/main/native/cpp/ErrorBase.cpp b/wpilibc/src/main/native/cpp/ErrorBase.cpp index a39d4fd000..8e70e61089 100644 --- a/wpilibc/src/main/native/cpp/ErrorBase.cpp +++ b/wpilibc/src/main/native/cpp/ErrorBase.cpp @@ -40,13 +40,13 @@ GlobalErrors& GlobalErrors::GetInstance() { void GlobalErrors::Insert(const Error& error) { GlobalErrors& inst = GetInstance(); - std::lock_guard lock(inst.mutex); + std::scoped_lock lock(inst.mutex); inst.lastError = &(*inst.errors.insert(error).first); } void GlobalErrors::Insert(Error&& error) { GlobalErrors& inst = GetInstance(); - std::lock_guard lock(inst.mutex); + std::scoped_lock lock(inst.mutex); inst.lastError = &(*inst.errors.insert(std::move(error)).first); } @@ -165,14 +165,14 @@ void ErrorBase::SetGlobalWPIError(const wpi::Twine& errorMessage, Error ErrorBase::GetGlobalError() { auto& inst = GlobalErrors::GetInstance(); - std::lock_guard mutex(inst.mutex); + std::scoped_lock mutex(inst.mutex); if (!inst.lastError) return Error{}; return *inst.lastError; } std::vector ErrorBase::GetGlobalErrors() { auto& inst = GlobalErrors::GetInstance(); - std::lock_guard mutex(inst.mutex); + std::scoped_lock mutex(inst.mutex); std::vector rv; for (auto&& error : inst.errors) rv.push_back(error); return rv; @@ -180,7 +180,7 @@ std::vector ErrorBase::GetGlobalErrors() { void ErrorBase::ClearGlobalErrors() { auto& inst = GlobalErrors::GetInstance(); - std::lock_guard mutex(inst.mutex); + std::scoped_lock mutex(inst.mutex); inst.errors.clear(); inst.lastError = nullptr; } diff --git a/wpilibc/src/main/native/cpp/MotorSafety.cpp b/wpilibc/src/main/native/cpp/MotorSafety.cpp index d60bc361f1..1806e86695 100644 --- a/wpilibc/src/main/native/cpp/MotorSafety.cpp +++ b/wpilibc/src/main/native/cpp/MotorSafety.cpp @@ -23,12 +23,12 @@ static wpi::SmallPtrSet instanceList; static wpi::mutex listMutex; MotorSafety::MotorSafety() { - std::lock_guard lock(listMutex); + std::scoped_lock lock(listMutex); instanceList.insert(this); } MotorSafety::~MotorSafety() { - std::lock_guard lock(listMutex); + std::scoped_lock lock(listMutex); instanceList.erase(this); } @@ -51,32 +51,32 @@ MotorSafety& MotorSafety::operator=(MotorSafety&& rhs) { } void MotorSafety::Feed() { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_stopTime = Timer::GetFPGATimestamp() + m_expiration; } void MotorSafety::SetExpiration(double expirationTime) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_expiration = expirationTime; } double MotorSafety::GetExpiration() const { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return m_expiration; } bool MotorSafety::IsAlive() const { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return !m_enabled || m_stopTime > Timer::GetFPGATimestamp(); } void MotorSafety::SetSafetyEnabled(bool enabled) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_enabled = enabled; } bool MotorSafety::IsSafetyEnabled() const { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return m_enabled; } @@ -85,7 +85,7 @@ void MotorSafety::Check() { double stopTime; { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); enabled = m_enabled; stopTime = m_stopTime; } @@ -106,7 +106,7 @@ void MotorSafety::Check() { } void MotorSafety::CheckMotors() { - std::lock_guard lock(listMutex); + std::scoped_lock lock(listMutex); for (auto elem : instanceList) { elem->Check(); } diff --git a/wpilibc/src/main/native/cpp/Notifier.cpp b/wpilibc/src/main/native/cpp/Notifier.cpp index 329e96ee53..19ca35ba85 100644 --- a/wpilibc/src/main/native/cpp/Notifier.cpp +++ b/wpilibc/src/main/native/cpp/Notifier.cpp @@ -35,7 +35,7 @@ Notifier::Notifier(TimerEventHandler handler) { TimerEventHandler handler; { - std::lock_guard lock(m_processMutex); + std::scoped_lock lock(m_processMutex); handler = m_handler; if (m_periodic) { m_expirationTime += m_period; @@ -91,12 +91,12 @@ Notifier& Notifier::operator=(Notifier&& rhs) { } void Notifier::SetHandler(TimerEventHandler handler) { - std::lock_guard lock(m_processMutex); + std::scoped_lock lock(m_processMutex); m_handler = handler; } void Notifier::StartSingle(double delay) { - std::lock_guard lock(m_processMutex); + std::scoped_lock lock(m_processMutex); m_periodic = false; m_period = delay; m_expirationTime = Timer::GetFPGATimestamp() + m_period; @@ -104,7 +104,7 @@ void Notifier::StartSingle(double delay) { } void Notifier::StartPeriodic(double period) { - std::lock_guard lock(m_processMutex); + std::scoped_lock lock(m_processMutex); m_periodic = true; m_period = period; m_expirationTime = Timer::GetFPGATimestamp() + m_period; diff --git a/wpilibc/src/main/native/cpp/PIDBase.cpp b/wpilibc/src/main/native/cpp/PIDBase.cpp index 0a42ef3554..e84d796e82 100644 --- a/wpilibc/src/main/native/cpp/PIDBase.cpp +++ b/wpilibc/src/main/native/cpp/PIDBase.cpp @@ -48,18 +48,18 @@ PIDBase::PIDBase(double Kp, double Ki, double Kd, double Kf, PIDSource& source, } double PIDBase::Get() const { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return m_result; } void PIDBase::SetContinuous(bool continuous) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_continuous = continuous; } void PIDBase::SetInputRange(double minimumInput, double maximumInput) { { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_minimumInput = minimumInput; m_maximumInput = maximumInput; m_inputRange = maximumInput - minimumInput; @@ -69,14 +69,14 @@ void PIDBase::SetInputRange(double minimumInput, double maximumInput) { } void PIDBase::SetOutputRange(double minimumOutput, double maximumOutput) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_minimumOutput = minimumOutput; m_maximumOutput = maximumOutput; } void PIDBase::SetPID(double p, double i, double d) { { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_P = p; m_I = i; m_D = d; @@ -84,7 +84,7 @@ void PIDBase::SetPID(double p, double i, double d) { } void PIDBase::SetPID(double p, double i, double d, double f) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_P = p; m_I = i; m_D = d; @@ -92,48 +92,48 @@ void PIDBase::SetPID(double p, double i, double d, double f) { } void PIDBase::SetP(double p) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_P = p; } void PIDBase::SetI(double i) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_I = i; } void PIDBase::SetD(double d) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_D = d; } void PIDBase::SetF(double f) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_F = f; } double PIDBase::GetP() const { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return m_P; } double PIDBase::GetI() const { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return m_I; } double PIDBase::GetD() const { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return m_D; } double PIDBase::GetF() const { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return m_F; } void PIDBase::SetSetpoint(double setpoint) { { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); if (m_maximumInput > m_minimumInput) { if (setpoint > m_maximumInput) @@ -149,19 +149,19 @@ void PIDBase::SetSetpoint(double setpoint) { } double PIDBase::GetSetpoint() const { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return m_setpoint; } double PIDBase::GetDeltaSetpoint() const { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return (m_setpoint - m_prevSetpoint) / m_setpointTimer.Get(); } double PIDBase::GetError() const { double setpoint = GetSetpoint(); { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return GetContinuousError(setpoint - m_pidInput->PIDGet()); } } @@ -177,32 +177,32 @@ PIDSourceType PIDBase::GetPIDSourceType() const { } void PIDBase::SetTolerance(double percent) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_toleranceType = kPercentTolerance; m_tolerance = percent; } void PIDBase::SetAbsoluteTolerance(double absTolerance) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_toleranceType = kAbsoluteTolerance; m_tolerance = absTolerance; } void PIDBase::SetPercentTolerance(double percent) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_toleranceType = kPercentTolerance; m_tolerance = percent; } void PIDBase::SetToleranceBuffer(int bufLength) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_filter = LinearFilter::MovingAverage(bufLength); } bool PIDBase::OnTarget() const { double error = GetError(); - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); switch (m_toleranceType) { case kPercentTolerance: return std::fabs(error) < m_tolerance / 100 * m_inputRange; @@ -218,7 +218,7 @@ bool PIDBase::OnTarget() const { } void PIDBase::Reset() { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_prevError = 0; m_totalError = 0; m_result = 0; @@ -246,7 +246,7 @@ void PIDBase::Calculate() { bool enabled; { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); enabled = m_enabled; } @@ -268,7 +268,7 @@ void PIDBase::Calculate() { double totalError; { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); input = m_filter.Calculate(m_pidInput->PIDGet()); @@ -308,7 +308,7 @@ void PIDBase::Calculate() { { // Ensures m_enabled check and PIDWrite() call occur atomically - std::lock_guard pidWriteLock(m_pidWriteMutex); + std::scoped_lock pidWriteLock(m_pidWriteMutex); std::unique_lock mainLock(m_thisMutex); if (m_enabled) { // Don't block other PIDBase operations on PIDWrite() @@ -318,7 +318,7 @@ void PIDBase::Calculate() { } } - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_prevError = m_error; m_error = error; m_totalError = totalError; diff --git a/wpilibc/src/main/native/cpp/PIDController.cpp b/wpilibc/src/main/native/cpp/PIDController.cpp index 05c54c1d6a..2e50360926 100644 --- a/wpilibc/src/main/native/cpp/PIDController.cpp +++ b/wpilibc/src/main/native/cpp/PIDController.cpp @@ -41,7 +41,7 @@ PIDController::~PIDController() { void PIDController::Enable() { { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_enabled = true; } } @@ -49,9 +49,9 @@ void PIDController::Enable() { void PIDController::Disable() { { // Ensures m_enabled modification and PIDWrite() call occur atomically - std::lock_guard pidWriteLock(m_pidWriteMutex); + std::scoped_lock pidWriteLock(m_pidWriteMutex); { - std::lock_guard mainLock(m_thisMutex); + std::scoped_lock mainLock(m_thisMutex); m_enabled = false; } @@ -68,7 +68,7 @@ void PIDController::SetEnabled(bool enable) { } bool PIDController::IsEnabled() const { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return m_enabled; } diff --git a/wpilibc/src/main/native/cpp/Resource.cpp b/wpilibc/src/main/native/cpp/Resource.cpp index bc61e55748..d5464611cb 100644 --- a/wpilibc/src/main/native/cpp/Resource.cpp +++ b/wpilibc/src/main/native/cpp/Resource.cpp @@ -16,7 +16,7 @@ wpi::mutex Resource::m_createMutex; void Resource::CreateResourceObject(std::unique_ptr& r, uint32_t elements) { - std::lock_guard lock(m_createMutex); + std::scoped_lock lock(m_createMutex); if (!r) { r = std::make_unique(elements); } @@ -27,7 +27,7 @@ Resource::Resource(uint32_t elements) { } uint32_t Resource::Allocate(const std::string& resourceDesc) { - std::lock_guard lock(m_allocateMutex); + std::scoped_lock lock(m_allocateMutex); for (uint32_t i = 0; i < m_isAllocated.size(); i++) { if (!m_isAllocated[i]) { m_isAllocated[i] = true; @@ -39,7 +39,7 @@ uint32_t Resource::Allocate(const std::string& resourceDesc) { } uint32_t Resource::Allocate(uint32_t index, const std::string& resourceDesc) { - std::lock_guard lock(m_allocateMutex); + std::scoped_lock lock(m_allocateMutex); if (index >= m_isAllocated.size()) { wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, resourceDesc); return std::numeric_limits::max(); diff --git a/wpilibc/src/main/native/cpp/SPI.cpp b/wpilibc/src/main/native/cpp/SPI.cpp index 5a2e7622bc..51341b0c67 100644 --- a/wpilibc/src/main/native/cpp/SPI.cpp +++ b/wpilibc/src/main/native/cpp/SPI.cpp @@ -28,7 +28,7 @@ class SPI::Accumulator { Accumulator(HAL_SPIPort port, int xferSize, int validMask, int validValue, int dataShift, int dataSize, bool isSigned, bool bigEndian) : m_notifier([=]() { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); Update(); }), m_buf(new uint32_t[(xferSize + 1) * kAccumulateDepth]), @@ -356,7 +356,7 @@ void SPI::FreeAccumulator() { void SPI::ResetAccumulator() { if (!m_accum) return; - std::lock_guard lock(m_accum->m_mutex); + std::scoped_lock lock(m_accum->m_mutex); m_accum->m_value = 0; m_accum->m_count = 0; m_accum->m_lastValue = 0; @@ -366,40 +366,40 @@ void SPI::ResetAccumulator() { void SPI::SetAccumulatorCenter(int center) { if (!m_accum) return; - std::lock_guard lock(m_accum->m_mutex); + std::scoped_lock lock(m_accum->m_mutex); m_accum->m_center = center; } void SPI::SetAccumulatorDeadband(int deadband) { if (!m_accum) return; - std::lock_guard lock(m_accum->m_mutex); + std::scoped_lock lock(m_accum->m_mutex); m_accum->m_deadband = deadband; } int SPI::GetAccumulatorLastValue() const { if (!m_accum) return 0; - std::lock_guard lock(m_accum->m_mutex); + std::scoped_lock lock(m_accum->m_mutex); m_accum->Update(); return m_accum->m_lastValue; } int64_t SPI::GetAccumulatorValue() const { if (!m_accum) return 0; - std::lock_guard lock(m_accum->m_mutex); + std::scoped_lock lock(m_accum->m_mutex); m_accum->Update(); return m_accum->m_value; } int64_t SPI::GetAccumulatorCount() const { if (!m_accum) return 0; - std::lock_guard lock(m_accum->m_mutex); + std::scoped_lock lock(m_accum->m_mutex); m_accum->Update(); return m_accum->m_count; } double SPI::GetAccumulatorAverage() const { if (!m_accum) return 0; - std::lock_guard lock(m_accum->m_mutex); + std::scoped_lock lock(m_accum->m_mutex); m_accum->Update(); if (m_accum->m_count == 0) return 0.0; return static_cast(m_accum->m_value) / m_accum->m_count; @@ -411,7 +411,7 @@ void SPI::GetAccumulatorOutput(int64_t& value, int64_t& count) const { count = 0; return; } - std::lock_guard lock(m_accum->m_mutex); + std::scoped_lock lock(m_accum->m_mutex); m_accum->Update(); value = m_accum->m_value; count = m_accum->m_count; @@ -419,20 +419,20 @@ void SPI::GetAccumulatorOutput(int64_t& value, int64_t& count) const { void SPI::SetAccumulatorIntegratedCenter(double center) { if (!m_accum) return; - std::lock_guard lock(m_accum->m_mutex); + std::scoped_lock lock(m_accum->m_mutex); m_accum->m_integratedCenter = center; } double SPI::GetAccumulatorIntegratedValue() const { if (!m_accum) return 0; - std::lock_guard lock(m_accum->m_mutex); + std::scoped_lock lock(m_accum->m_mutex); m_accum->Update(); return m_accum->m_integratedValue; } double SPI::GetAccumulatorIntegratedAverage() const { if (!m_accum) return 0; - std::lock_guard lock(m_accum->m_mutex); + std::scoped_lock lock(m_accum->m_mutex); m_accum->Update(); if (m_accum->m_count <= 1) return 0.0; // count-1 due to not integrating the first value received diff --git a/wpilibc/src/main/native/cpp/Timer.cpp b/wpilibc/src/main/native/cpp/Timer.cpp index 3201e711c4..c95802edc1 100644 --- a/wpilibc/src/main/native/cpp/Timer.cpp +++ b/wpilibc/src/main/native/cpp/Timer.cpp @@ -58,7 +58,7 @@ double Timer::Get() const { double result; double currentTime = GetFPGATimestamp(); - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (m_running) { // If the current time is before the start time, then the FPGA clock rolled // over. Compensate by adding the ~71 minutes that it takes to roll over to @@ -76,13 +76,13 @@ double Timer::Get() const { } void Timer::Reset() { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_accumulatedTime = 0; m_startTime = GetFPGATimestamp(); } void Timer::Start() { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (!m_running) { m_startTime = GetFPGATimestamp(); m_running = true; @@ -92,7 +92,7 @@ void Timer::Start() { void Timer::Stop() { double temp = Get(); - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (m_running) { m_accumulatedTime = temp; m_running = false; @@ -101,7 +101,7 @@ void Timer::Stop() { bool Timer::HasPeriodPassed(double period) { if (Get() > period) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); // Advance the start time by the period. m_startTime += period; // Don't set it to the current time... we want to avoid drift. diff --git a/wpilibc/src/main/native/cpp/commands/Scheduler.cpp b/wpilibc/src/main/native/cpp/commands/Scheduler.cpp index 2815625b41..a51cfc8dd8 100644 --- a/wpilibc/src/main/native/cpp/commands/Scheduler.cpp +++ b/wpilibc/src/main/native/cpp/commands/Scheduler.cpp @@ -51,7 +51,7 @@ Scheduler* Scheduler::GetInstance() { } void Scheduler::AddCommand(Command* command) { - std::lock_guard lock(m_impl->additionsMutex); + std::scoped_lock lock(m_impl->additionsMutex); if (std::find(m_impl->additions.begin(), m_impl->additions.end(), command) != m_impl->additions.end()) return; @@ -59,7 +59,7 @@ void Scheduler::AddCommand(Command* command) { } void Scheduler::AddButton(ButtonScheduler* button) { - std::lock_guard lock(m_impl->buttonsMutex); + std::scoped_lock lock(m_impl->buttonsMutex); m_impl->buttons.emplace_back(button); } @@ -76,7 +76,7 @@ void Scheduler::Run() { { if (!m_impl->enabled) return; - std::lock_guard lock(m_impl->buttonsMutex); + std::scoped_lock lock(m_impl->buttonsMutex); for (auto& button : m_impl->buttons) { button->Execute(); } @@ -103,7 +103,7 @@ void Scheduler::Run() { // Add the new things { - std::lock_guard lock(m_impl->additionsMutex); + std::scoped_lock lock(m_impl->additionsMutex); for (auto& addition : m_impl->additions) { // Check to make sure no adding during adding if (m_impl->adding) { diff --git a/wpilibc/src/main/native/cpp/controller/PIDController.cpp b/wpilibc/src/main/native/cpp/controller/PIDController.cpp index 37ab403411..4d25298396 100644 --- a/wpilibc/src/main/native/cpp/controller/PIDController.cpp +++ b/wpilibc/src/main/native/cpp/controller/PIDController.cpp @@ -73,44 +73,44 @@ PIDController& PIDController::operator=(PIDController&& rhs) { } void PIDController::SetP(double Kp) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_Kp = Kp; } void PIDController::SetI(double Ki) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_Ki = Ki; } void PIDController::SetD(double Kd) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_Kd = Kd; } double PIDController::GetP() const { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return m_Kp; } double PIDController::GetI() const { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return m_Ki; } double PIDController::GetD() const { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return m_Kd; } double PIDController::GetPeriod() const { return m_period; } double PIDController::GetOutput() const { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return m_output; } void PIDController::SetSetpoint(double setpoint) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); if (m_maximumInput > m_minimumInput) { m_setpoint = std::clamp(setpoint, m_minimumInput, m_maximumInput); @@ -120,7 +120,7 @@ void PIDController::SetSetpoint(double setpoint) { } double PIDController::GetSetpoint() const { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return m_setpoint; } @@ -128,7 +128,7 @@ bool PIDController::AtSetpoint(double tolerance, double deltaTolerance, Tolerance toleranceType) const { double deltaError = GetDeltaError(); - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); if (toleranceType == Tolerance::kPercent) { return std::abs(m_currError) < tolerance / 100 * m_inputRange && std::abs(deltaError) < deltaTolerance / 100 * m_inputRange; @@ -143,12 +143,12 @@ bool PIDController::AtSetpoint() const { } void PIDController::SetContinuous(bool continuous) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_continuous = continuous; } void PIDController::SetInputRange(double minimumInput, double maximumInput) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_minimumInput = minimumInput; m_maximumInput = maximumInput; m_inputRange = maximumInput - minimumInput; @@ -160,14 +160,14 @@ void PIDController::SetInputRange(double minimumInput, double maximumInput) { } void PIDController::SetOutputRange(double minimumOutput, double maximumOutput) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_minimumOutput = minimumOutput; m_maximumOutput = maximumOutput; } void PIDController::SetAbsoluteTolerance(double tolerance, double deltaTolerance) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_toleranceType = Tolerance::kAbsolute; m_tolerance = tolerance; m_deltaTolerance = deltaTolerance; @@ -175,14 +175,14 @@ void PIDController::SetAbsoluteTolerance(double tolerance, void PIDController::SetPercentTolerance(double tolerance, double deltaTolerance) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_toleranceType = Tolerance::kPercent; m_tolerance = tolerance; m_deltaTolerance = deltaTolerance; } double PIDController::GetError() const { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return GetContinuousError(m_currError); } @@ -192,17 +192,17 @@ double PIDController::GetError() const { * @return The change in error per second. */ double PIDController::GetDeltaError() const { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return (m_currError - m_prevError) / GetPeriod(); } double PIDController::Calculate(double measurement) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return CalculateUnsafe(measurement); } double PIDController::Calculate(double measurement, double setpoint) { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); // Set setpoint to provided value if (m_maximumInput > m_minimumInput) { @@ -215,7 +215,7 @@ double PIDController::Calculate(double measurement, double setpoint) { } void PIDController::Reset() { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_prevError = 0; m_totalError = 0; m_output = 0; diff --git a/wpilibc/src/main/native/cpp/controller/PIDControllerRunner.cpp b/wpilibc/src/main/native/cpp/controller/PIDControllerRunner.cpp index 40f61efdb5..06d621fb08 100644 --- a/wpilibc/src/main/native/cpp/controller/PIDControllerRunner.cpp +++ b/wpilibc/src/main/native/cpp/controller/PIDControllerRunner.cpp @@ -25,16 +25,16 @@ PIDControllerRunner::PIDControllerRunner( PIDControllerRunner::~PIDControllerRunner() { Disable(); } void PIDControllerRunner::Enable() { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); m_enabled = true; } void PIDControllerRunner::Disable() { // Ensures m_enabled modification and m_controllerOutput() call occur // atomically - std::lock_guard outputLock(m_outputMutex); + std::scoped_lock outputLock(m_outputMutex); { - std::lock_guard mainLock(m_thisMutex); + std::scoped_lock mainLock(m_thisMutex); m_enabled = false; } @@ -42,13 +42,13 @@ void PIDControllerRunner::Disable() { } bool PIDControllerRunner::IsEnabled() const { - std::lock_guard lock(m_thisMutex); + std::scoped_lock lock(m_thisMutex); return m_enabled; } void PIDControllerRunner::Run() { // Ensures m_enabled check and m_controllerOutput() call occur atomically - std::lock_guard outputLock(m_outputMutex); + std::scoped_lock outputLock(m_outputMutex); std::unique_lock mainLock(m_thisMutex); if (m_enabled) { // Don't block other PIDControllerRunner operations on output diff --git a/wpilibc/src/main/native/cpp/livewindow/LiveWindow.cpp b/wpilibc/src/main/native/cpp/livewindow/LiveWindow.cpp index 50ac2c7e44..7a4f1a38c7 100644 --- a/wpilibc/src/main/native/cpp/livewindow/LiveWindow.cpp +++ b/wpilibc/src/main/native/cpp/livewindow/LiveWindow.cpp @@ -61,7 +61,7 @@ LiveWindow* LiveWindow::GetInstance() { } void LiveWindow::Add(std::shared_ptr sendable) { - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); auto& comp = m_impl->components[sendable.get()]; comp.sendable = sendable; } @@ -75,19 +75,19 @@ void LiveWindow::AddChild(Sendable* parent, std::shared_ptr child) { } void LiveWindow::AddChild(Sendable* parent, void* child) { - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); auto& comp = m_impl->components[child]; comp.parent = parent; comp.telemetryEnabled = false; } void LiveWindow::Remove(Sendable* sendable) { - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); m_impl->components.erase(sendable); } void LiveWindow::EnableTelemetry(Sendable* sendable) { - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); // Re-enable global setting in case DisableAllTelemetry() was called. m_impl->telemetryEnabled = true; auto i = m_impl->components.find(sendable); @@ -95,24 +95,24 @@ void LiveWindow::EnableTelemetry(Sendable* sendable) { } void LiveWindow::DisableTelemetry(Sendable* sendable) { - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); auto i = m_impl->components.find(sendable); if (i != m_impl->components.end()) i->getSecond().telemetryEnabled = false; } void LiveWindow::DisableAllTelemetry() { - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); m_impl->telemetryEnabled = false; for (auto& i : m_impl->components) i.getSecond().telemetryEnabled = false; } bool LiveWindow::IsEnabled() const { - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); return m_impl->liveWindowEnabled; } void LiveWindow::SetEnabled(bool enabled) { - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); if (m_impl->liveWindowEnabled == enabled) return; Scheduler* scheduler = Scheduler::GetInstance(); m_impl->startLiveWindow = enabled; @@ -132,7 +132,7 @@ void LiveWindow::SetEnabled(bool enabled) { } void LiveWindow::UpdateValues() { - std::lock_guard lock(m_impl->mutex); + std::scoped_lock lock(m_impl->mutex); UpdateValuesUnsafe(); } diff --git a/wpilibc/src/main/native/cpp/smartdashboard/SendableBase.cpp b/wpilibc/src/main/native/cpp/smartdashboard/SendableBase.cpp index 8e8b3a4616..4110b1fdfd 100644 --- a/wpilibc/src/main/native/cpp/smartdashboard/SendableBase.cpp +++ b/wpilibc/src/main/native/cpp/smartdashboard/SendableBase.cpp @@ -34,22 +34,22 @@ SendableBase& SendableBase::operator=(SendableBase&& rhs) { } std::string SendableBase::GetName() const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); return m_name; } void SendableBase::SetName(const wpi::Twine& name) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_name = name.str(); } std::string SendableBase::GetSubsystem() const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); return m_subsystem; } void SendableBase::SetSubsystem(const wpi::Twine& subsystem) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_subsystem = subsystem.str(); } diff --git a/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp b/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp index 0ab47f28a6..ac667a3fcd 100644 --- a/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp +++ b/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp @@ -97,7 +97,7 @@ void SmartDashboard::PutData(wpi::StringRef key, Sendable* data) { return; } auto& inst = Singleton::GetInstance(); - std::lock_guard lock(inst.tablesToDataMutex); + std::scoped_lock lock(inst.tablesToDataMutex); auto& sddata = inst.tablesToData[key]; if (!sddata.sendable || sddata.sendable != data) { sddata = SmartDashboardData(data); @@ -120,7 +120,7 @@ void SmartDashboard::PutData(Sendable* value) { Sendable* SmartDashboard::GetData(wpi::StringRef key) { auto& inst = Singleton::GetInstance(); - std::lock_guard lock(inst.tablesToDataMutex); + std::scoped_lock lock(inst.tablesToDataMutex); auto data = inst.tablesToData.find(key); if (data == inst.tablesToData.end()) { wpi_setGlobalWPIErrorWithContext(SmartDashboardMissingKey, key); @@ -256,7 +256,7 @@ std::shared_ptr SmartDashboard::GetValue(wpi::StringRef keyName) { void SmartDashboard::UpdateValues() { auto& inst = Singleton::GetInstance(); - std::lock_guard lock(inst.tablesToDataMutex); + std::scoped_lock lock(inst.tablesToDataMutex); for (auto& i : inst.tablesToData) { i.getValue().builder.UpdateTable(); } diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc index 69a803a95a..295d263015 100644 --- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc +++ b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc @@ -62,7 +62,7 @@ auto SendableChooser::GetSelected() -> decltype(_unwrap_smart_ptr(m_choices[""])) { std::string selected = m_defaultChoice; { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (m_haveSelected) selected = m_selected; } if (selected.empty()) { @@ -99,7 +99,7 @@ void SendableChooser::InitSendable(SendableBuilder& builder) { builder.AddSmallStringProperty( kActive, [=](wpi::SmallVectorImpl& buf) -> wpi::StringRef { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (m_haveSelected) { buf.assign(m_selected.begin(), m_selected.end()); return wpi::StringRef(buf.data(), buf.size()); @@ -109,11 +109,11 @@ void SendableChooser::InitSendable(SendableBuilder& builder) { }, nullptr); { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_activeEntries.emplace_back(builder.GetEntry(kActive)); } builder.AddStringProperty(kSelected, nullptr, [=](wpi::StringRef val) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_haveSelected = true; m_selected = val; for (auto& entry : m_activeEntries) entry.SetString(val); diff --git a/wpiutil/src/main/native/cpp/SafeThread.cpp b/wpiutil/src/main/native/cpp/SafeThread.cpp index 42143686cb..3a906bd9c5 100644 --- a/wpiutil/src/main/native/cpp/SafeThread.cpp +++ b/wpiutil/src/main/native/cpp/SafeThread.cpp @@ -29,7 +29,7 @@ detail::SafeThreadOwnerBase::~SafeThreadOwnerBase() { } void detail::SafeThreadOwnerBase::Start(std::shared_ptr thr) { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (auto thr = m_thread.lock()) return; m_stdThread = std::thread([=] { thr->Main(); }); thr->m_threadId = m_stdThread.get_id(); @@ -37,7 +37,7 @@ void detail::SafeThreadOwnerBase::Start(std::shared_ptr thr) { } void detail::SafeThreadOwnerBase::Stop() { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); if (auto thr = m_thread.lock()) { thr->m_active = false; thr->m_cond.notify_all(); @@ -63,26 +63,24 @@ void detail::SafeThreadOwnerBase::Join() { void detail::swap(SafeThreadOwnerBase& lhs, SafeThreadOwnerBase& rhs) noexcept { using std::swap; if (&lhs == &rhs) return; - std::lock(lhs.m_mutex, rhs.m_mutex); - std::lock_guard lock_lhs(lhs.m_mutex, std::adopt_lock); - std::lock_guard lock_rhs(rhs.m_mutex, std::adopt_lock); + std::scoped_lock lock(lhs.m_mutex, rhs.m_mutex); std::swap(lhs.m_stdThread, rhs.m_stdThread); std::swap(lhs.m_thread, rhs.m_thread); } detail::SafeThreadOwnerBase::operator bool() const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); return !m_thread.expired(); } std::thread::native_handle_type detail::SafeThreadOwnerBase::GetNativeThreadHandle() { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); return m_stdThread.native_handle(); } std::shared_ptr detail::SafeThreadOwnerBase::GetThreadSharedPtr() const { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); return m_thread.lock(); } diff --git a/wpiutil/src/main/native/cpp/TCPConnector_parallel.cpp b/wpiutil/src/main/native/cpp/TCPConnector_parallel.cpp index ded436fa38..de8bc2cbbe 100644 --- a/wpiutil/src/main/native/cpp/TCPConnector_parallel.cpp +++ b/wpiutil/src/main/native/cpp/TCPConnector_parallel.cpp @@ -74,7 +74,7 @@ std::unique_ptr TCPConnector::connect_parallel( // don't start a new worker if we had a previously still-active connection // attempt to the same server { - std::lock_guard lock(local->mtx); + std::scoped_lock lock(local->mtx); if (local->active.count(active_tracker) > 0) continue; // already in set } @@ -85,7 +85,7 @@ std::unique_ptr TCPConnector::connect_parallel( if (!result->done) { // add to global state { - std::lock_guard lock(local->mtx); + std::scoped_lock lock(local->mtx); local->active.insert(active_tracker); } @@ -95,13 +95,13 @@ std::unique_ptr TCPConnector::connect_parallel( // remove from global state { - std::lock_guard lock(local->mtx); + std::scoped_lock lock(local->mtx); local->active.erase(active_tracker); } // successful connection if (stream) { - std::lock_guard lock(result->mtx); + std::scoped_lock lock(result->mtx); if (!result->done.exchange(true)) result->stream = std::move(stream); } } diff --git a/wpiutil/src/main/native/cpp/llvm/ErrorHandling.cpp b/wpiutil/src/main/native/cpp/llvm/ErrorHandling.cpp index bac9ace4f0..ef79456779 100644 --- a/wpiutil/src/main/native/cpp/llvm/ErrorHandling.cpp +++ b/wpiutil/src/main/native/cpp/llvm/ErrorHandling.cpp @@ -55,14 +55,14 @@ static std::mutex BadAllocErrorHandlerMutex; void wpi::install_fatal_error_handler(fatal_error_handler_t handler, void *user_data) { - std::lock_guard Lock(ErrorHandlerMutex); + std::scoped_lock Lock(ErrorHandlerMutex); assert(!ErrorHandler && "Error handler already registered!\n"); ErrorHandler = handler; ErrorHandlerUserData = user_data; } void wpi::remove_fatal_error_handler() { - std::lock_guard Lock(ErrorHandlerMutex); + std::scoped_lock Lock(ErrorHandlerMutex); ErrorHandler = nullptr; ErrorHandlerUserData = nullptr; } @@ -85,7 +85,7 @@ void wpi::report_fatal_error(const Twine &Reason, bool GenCrashDiag) { { // Only acquire the mutex while reading the handler, so as not to invoke a // user-supplied callback under a lock. - std::lock_guard Lock(ErrorHandlerMutex); + std::scoped_lock Lock(ErrorHandlerMutex); handler = ErrorHandler; handlerData = ErrorHandlerUserData; } @@ -113,14 +113,14 @@ void wpi::report_fatal_error(const Twine &Reason, bool GenCrashDiag) { void wpi::install_bad_alloc_error_handler(fatal_error_handler_t handler, void *user_data) { - std::lock_guard Lock(BadAllocErrorHandlerMutex); + std::scoped_lock Lock(BadAllocErrorHandlerMutex); assert(!ErrorHandler && "Bad alloc error handler already registered!\n"); BadAllocErrorHandler = handler; BadAllocErrorHandlerUserData = user_data; } void wpi::remove_bad_alloc_error_handler() { - std::lock_guard Lock(BadAllocErrorHandlerMutex); + std::scoped_lock Lock(BadAllocErrorHandlerMutex); BadAllocErrorHandler = nullptr; BadAllocErrorHandlerUserData = nullptr; } @@ -131,7 +131,7 @@ void wpi::report_bad_alloc_error(const char *Reason, bool GenCrashDiag) { { // Only acquire the mutex while reading the handler, so as not to invoke a // user-supplied callback under a lock. - std::lock_guard Lock(BadAllocErrorHandlerMutex); + std::scoped_lock Lock(BadAllocErrorHandlerMutex); Handler = BadAllocErrorHandler; HandlerData = BadAllocErrorHandlerUserData; } diff --git a/wpiutil/src/main/native/cpp/llvm/ManagedStatic.cpp b/wpiutil/src/main/native/cpp/llvm/ManagedStatic.cpp index 5274a437d3..0cfe58ac7a 100644 --- a/wpiutil/src/main/native/cpp/llvm/ManagedStatic.cpp +++ b/wpiutil/src/main/native/cpp/llvm/ManagedStatic.cpp @@ -33,7 +33,7 @@ static wpi::mutex* getManagedStaticMutex() { void ManagedStaticBase::RegisterManagedStatic(void *(*Creator)(), void (*Deleter)(void*)) const { assert(Creator); - std::lock_guard Lock(*getManagedStaticMutex()); + std::scoped_lock Lock(*getManagedStaticMutex()); if (!Ptr.load(std::memory_order_relaxed)) { void *Tmp = Creator(); @@ -65,7 +65,7 @@ void ManagedStaticBase::destroy() const { /// wpi_shutdown - Deallocate and destroy all ManagedStatic variables. void wpi::wpi_shutdown() { - std::lock_guard Lock(*getManagedStaticMutex()); + std::scoped_lock Lock(*getManagedStaticMutex()); while (StaticList) StaticList->destroy(); diff --git a/wpiutil/src/main/native/include/wpi/Signal.h b/wpiutil/src/main/native/include/wpi/Signal.h index c53a2aa5a0..d8109ff3ef 100644 --- a/wpiutil/src/main/native/include/wpi/Signal.h +++ b/wpiutil/src/main/native/include/wpi/Signal.h @@ -548,9 +548,7 @@ public: } SignalBase & operator=(SignalBase && o) { - lock_type lock1(m_mutex, std::defer_lock); - lock_type lock2(o.m_mutex, std::defer_lock); - std::lock(lock1, lock2); + std::scoped_lock lock(m_mutex, o.m_mutex); std::swap(m_func, o.m_func); m_block.store(o.m_block.exchange(m_block.load())); diff --git a/wpiutil/src/main/native/include/wpi/priority_mutex.h b/wpiutil/src/main/native/include/wpi/priority_mutex.h index 4e23fac555..bb16289201 100644 --- a/wpiutil/src/main/native/include/wpi/priority_mutex.h +++ b/wpiutil/src/main/native/include/wpi/priority_mutex.h @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) 2016-2018 FIRST. All Rights Reserved. */ +/* Copyright (c) 2016-2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -7,7 +7,7 @@ #pragma once -// Allows usage with std::lock_guard without including separately +// Allows usage with std::scoped_lock without including separately #ifdef __linux__ #include #endif diff --git a/wpiutil/src/main/native/include/wpi/uv/Async.h b/wpiutil/src/main/native/include/wpi/uv/Async.h index f197fad950..2da870dfce 100644 --- a/wpiutil/src/main/native/include/wpi/uv/Async.h +++ b/wpiutil/src/main/native/include/wpi/uv/Async.h @@ -68,7 +68,7 @@ class Async final : public HandleImpl, uv_async_t> { int err = uv_async_init(loop->GetRaw(), h->GetRaw(), [](uv_async_t* handle) { auto& h = *static_cast(handle->data); - std::lock_guard lock(h.m_mutex); + std::scoped_lock lock(h.m_mutex); for (auto&& v : h.m_data) std::apply(h.wakeup, v); h.m_data.clear(); }); @@ -96,7 +96,7 @@ class Async final : public HandleImpl, uv_async_t> { } { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_data.emplace_back(std::forward_as_tuple(std::forward(u)...)); } if (loop) this->Invoke(&uv_async_send, this->GetRaw()); diff --git a/wpiutil/src/main/native/include/wpi/uv/AsyncFunction.h b/wpiutil/src/main/native/include/wpi/uv/AsyncFunction.h index 6cd06723ea..4510b840b3 100644 --- a/wpiutil/src/main/native/include/wpi/uv/AsyncFunction.h +++ b/wpiutil/src/main/native/include/wpi/uv/AsyncFunction.h @@ -132,7 +132,7 @@ class AsyncFunction final // add the parameters to the input queue { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_params.emplace_back(std::piecewise_construct, std::forward_as_tuple(req), std::forward_as_tuple(std::forward(u)...)); diff --git a/wpiutil/src/test/native/cpp/priority_mutex_test.cpp b/wpiutil/src/test/native/cpp/priority_mutex_test.cpp index 9b1d726609..448a757851 100644 --- a/wpiutil/src/test/native/cpp/priority_mutex_test.cpp +++ b/wpiutil/src/test/native/cpp/priority_mutex_test.cpp @@ -32,7 +32,7 @@ class Notification { } // Sets the condition to true, and wakes all waiting threads. void Notify() { - std::lock_guard lock(m_mutex); + std::scoped_lock lock(m_mutex); m_set = true; m_condition.notify_all(); } diff --git a/wpiutil/src/test/native/cpp/spinlock_bench.cpp b/wpiutil/src/test/native/cpp/spinlock_bench.cpp index 70061513b2..b36e55804b 100644 --- a/wpiutil/src/test/native/cpp/spinlock_bench.cpp +++ b/wpiutil/src/test/native/cpp/spinlock_bench.cpp @@ -35,7 +35,7 @@ TEST(SpinlockTest, Benchmark) { auto start = high_resolution_clock::now(); for (int i = 0; i < 10000000; i++) { - std::lock_guard lock(std_mutex); + std::scoped_lock lock(std_mutex); ++value; } auto stop = high_resolution_clock::now(); @@ -49,7 +49,7 @@ TEST(SpinlockTest, Benchmark) { auto start = high_resolution_clock::now(); for (int i = 0; i < 1000000; i++) { - std::lock_guard lock(std_mutex); + std::scoped_lock lock(std_mutex); ++value; } auto stop = high_resolution_clock::now(); @@ -64,7 +64,7 @@ TEST(SpinlockTest, Benchmark) { auto start = high_resolution_clock::now(); for (int i = 0; i < 1000000; i++) { - std::lock_guard lock(std_recursive_mutex); + std::scoped_lock lock(std_recursive_mutex); ++value; } auto stop = high_resolution_clock::now(); @@ -79,7 +79,7 @@ TEST(SpinlockTest, Benchmark) { auto start = high_resolution_clock::now(); for (int i = 0; i < 1000000; i++) { - std::lock_guard lock(wpi_mutex); + std::scoped_lock lock(wpi_mutex); ++value; } auto stop = high_resolution_clock::now(); @@ -94,7 +94,7 @@ TEST(SpinlockTest, Benchmark) { auto start = high_resolution_clock::now(); for (int i = 0; i < 1000000; i++) { - std::lock_guard lock(wpi_recursive_mutex); + std::scoped_lock lock(wpi_recursive_mutex); ++value; } auto stop = high_resolution_clock::now(); @@ -109,7 +109,7 @@ TEST(SpinlockTest, Benchmark) { auto start = high_resolution_clock::now(); for (int i = 0; i < 1000000; i++) { - std::lock_guard lock(spinlock); + std::scoped_lock lock(spinlock); ++value; } auto stop = high_resolution_clock::now(); @@ -124,7 +124,7 @@ TEST(SpinlockTest, Benchmark) { auto start = high_resolution_clock::now(); for (int i = 0; i < 1000000; i++) { - std::lock_guard lock(recursive_spinlock1); + std::scoped_lock lock(recursive_spinlock1); ++value; } auto stop = high_resolution_clock::now(); @@ -139,7 +139,7 @@ TEST(SpinlockTest, Benchmark) { auto start = high_resolution_clock::now(); for (int i = 0; i < 1000000; i++) { - std::lock_guard lock(recursive_spinlock2); + std::scoped_lock lock(recursive_spinlock2); ++value; } auto stop = high_resolution_clock::now(); @@ -154,7 +154,7 @@ TEST(SpinlockTest, Benchmark) { auto start = high_resolution_clock::now(); for (int i = 0; i < 1000000; i++) { - std::lock_guard lock(recursive_spinlock); + std::scoped_lock lock(recursive_spinlock); ++value; } auto stop = high_resolution_clock::now();