Add Thread Guard for debugging simple threading issues (#4254)

* Add ThreadGuard class

* Use ThreadGuard when accessing a ChannelView's messageSnapshot
This commit is contained in:
pajlada 2022-12-24 11:32:08 +01:00 committed by GitHub
parent 2ba4da02ae
commit b9308d7325
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 39 additions and 0 deletions

View file

@ -364,6 +364,7 @@ set(SOURCE_FILES
util/StreamLink.hpp
util/StreamerMode.cpp
util/StreamerMode.hpp
util/ThreadGuard.hpp
util/Twitch.cpp
util/Twitch.hpp
util/TypeName.hpp

35
src/util/ThreadGuard.hpp Normal file
View file

@ -0,0 +1,35 @@
#pragma once
#include <cassert>
#include <mutex>
#include <optional>
#include <thread>
namespace chatterino {
// Debug-class which asserts if guard of the same object has been called from different threads
struct ThreadGuard {
#ifndef NDEBUG
std::mutex mutex;
std::optional<std::thread::id> threadID;
#endif
inline void guard()
{
#ifndef NDEBUG
std::unique_lock lock(this->mutex);
auto currentThreadID = std::this_thread::get_id();
if (!this->threadID.has_value())
{
this->threadID = currentThreadID;
return;
}
assert(this->threadID == currentThreadID);
#endif
}
};
} // namespace chatterino

View file

@ -628,6 +628,7 @@ const boost::optional<MessageElementFlags> &ChannelView::getOverrideFlags()
LimitedQueueSnapshot<MessageLayoutPtr> &ChannelView::getMessagesSnapshot()
{
this->snapshotGuard_.guard();
if (!this->paused() /*|| this->scrollBar_->isVisible()*/)
{
this->snapshot_ = this->messages_.getSnapshot();

View file

@ -6,6 +6,7 @@
#include "messages/LimitedQueue.hpp"
#include "messages/LimitedQueueSnapshot.hpp"
#include "messages/Selection.hpp"
#include "util/ThreadGuard.hpp"
#include "widgets/BaseWidget.hpp"
#include <pajlada/signals/signal.hpp>
@ -270,6 +271,7 @@ private:
boost::optional<MessageElementFlags> overrideFlags_;
MessageLayoutPtr lastReadMessage_;
ThreadGuard snapshotGuard_;
LimitedQueueSnapshot<MessageLayoutPtr> snapshot_;
ChannelPtr channel_ = nullptr;