Ami Tavory
Ami Tavory

Reputation: 76346

A thread_guard Equivalent To lock_guard / unique_lock

The standard library provides a mutex class, with the ability to manually lock and unlock it:

std::mutex m;
m.lock();
// ...
m.unlock();

However, the library apparently also recognizes that a common case is just to lock the mutex at some point, and unlock it when leaving a block. For this it provides std::lock_guard and std::unique_lock:

std::mutex m;
std::lock_guard<std::mutex> lock(m);
// ...

// Automatic unlock

I think a fairly common pattern for threads, is to create one (either as a stack variable, or a member), then join it before destructing it:

std::thread t(foo);
// ...
t.join();

It seems easy to write a thread_guard, which would take a thread (or a sequence of threads), and would just call join on its own destruction:

std::thread t(foo);
thread_guard<std::thread> g(t);
// ...
// Join automatically
  1. Is there a standard-library class like it?

  2. If not, is there some reason to avoid this?

Upvotes: 2

Views: 730

Answers (1)

Hayt
Hayt

Reputation: 5370

This issue is discussed in Scott Meyer's book "Modern Effective c++"

The problem is that if there would be another default behavior (detach or join) would cause hard to find errors in case you forget that there is a implicit operation. So the actual default behavior on destruction is asserting if not explicitly joined or detached. And no "Guard" class is there also because of that reason.

If you always want to join it's safe to write such a class yourself. But when someone uses it and wants to detach people can forget that the destructor will implicitly join it. So that's the risk in writing such function.

As an alternative you can use a scope_guard by boost or the folly library (which I personally prefer more) and declare in the beginning explicitly your intention and it will be executed. Or you can write a policy based "Guard" class where you have to explicitly state what you want to do on destruction.

Upvotes: 4

Related Questions