Created
July 13, 2020 09:02
-
-
Save hnrck/1bc7de8d4f9eab866fbde1d91c26a816 to your computer and use it in GitHub Desktop.
C++17 thread guard implementation for RAII strategy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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