Skip to content

Instantly share code, notes, and snippets.

@hnrck
Created July 13, 2020 09:02
Show Gist options
  • Save hnrck/1bc7de8d4f9eab866fbde1d91c26a816 to your computer and use it in GitHub Desktop.
Save hnrck/1bc7de8d4f9eab866fbde1d91c26a816 to your computer and use it in GitHub Desktop.
C++17 thread guard implementation for RAII strategy
#include <iostream>
#include <thread>
#include <mutex>
#include "thread_guard.h"
int main() {
auto x = 0u;
auto m = std::mutex();
{
const auto tg = thread_guard(std::thread([](unsigned int &x, std::mutex &m){ const std::lock_guard<std::mutex> lock(m); ++x; }, std::ref(x), std::ref(m)));
std::cout << "computing x" << std::endl;
}
std::cout << x << std::endl;
return 0;
}
CXX?=g++
BIN?=main
EXT?=cpp
LINKS?=pthread
CXXSTD?=c++17
SRCS=$(shell find . -name "*."$(EXT))
DIRS=$(shell find ./* -type d)
OBJS=$(patsubst %.$(EXT),%.o,$(SRCS))
INCS=$(addprefix -I, $(DIRS))
CXXFLAGS+=-std=$(CXXSTD) -Wall $(INCS)
LDFLAGS+=$(addprefix -l, $(LINKS))
.PHONY: all run clean
all: $(BIN)
$(EXT).o: $(SRCS)
$(CXX) $(CPPFLAGS) -c $<
$(BIN): $(OBJS)
$(CXX) $(CXXFLAGS) -o $(BIN) $(notdir $(OBJS)) $(LDFLAGS)
run: all
-./$(BIN)
clean:
-rm -f $(notdir $(OBJS)) $(BIN)
#ifndef THREAD_GUARD
#define THREAD_GUARD
class thread_guard final {
private:
std::thread th_;
public:
explicit thread_guard(std::thread th) : th_{std::move(th)} {}
~thread_guard() {
join();
}
void join() {
if (th_.joinable()) {
th_.join();
}
}
thread_guard(const thread_guard &) = delete;
thread_guard &operator=(const thread_guard &) = delete;
thread_guard(thread_guard &&) = default;
thread_guard &operator=(thread_guard &&) = default;
};
#endif // THREAD_GUARD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment