Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

return std::move(std::thread) in std::lock_guard

32 views
Skip to first unread message

Marcel Mueller

unread,
Aug 15, 2022, 8:11:13 AM8/15/22
to
Assuming a thread manages its own resource, i.e. it shall destroy itself
when it receives a command to do so. Something like this:

class WorkerThread
{
enum Action : unsigned char
{ IDLE,
// ...
DIE
} Command;
std::mutex Lock;
std::condition_variable CV;
std::thread Worker;

void ThreadFunc()
{
{ std::unique_lock<std::mutex> lock(Lock);
while (true)
{
CV.wait(lock, [this]() { return Command != IDLE; });

lock.unlock();
// process commands...
lock.lock();

if (State == DIE)
break;

Command = IDLE;
CV.notify_one();
}
}

delete this;
}

public:
// ...

std::thread Dispose()
{
std::lock_guard<std::mutex> lock(Lock);
Command = DIE;
CV.notify_one();
return std::move(Worker); // <-- HERE!!!
}
}

The question is:
Does "return std::move" within the lock ensure that this->Worker is no
longer joinable and the thread ownership is transferred before the mutex
is unlocked?

The idea is that the termination command (unlike others) is sent without
waiting for the worker to finish its last command. The thread will
finish asynchronously and Dispose will return (almost) immediately.
But this is part of a plug-in (ladspa) and I need to join the thread if
the plug-in happens to get unloaded before the thread has finally ended.
So I return the std::thread instance from Dispose, leaving a not
joinable instance in the class. Typically the thread terminates far
before the plug-in gets unloaded.


Marcel

Juha Nieminen

unread,
Aug 15, 2022, 8:18:11 AM8/15/22
to
Marcel Mueller <news.5...@spamgourmet.org> wrote:
> delete this;

Unrelated to your question, but is that supported by the standard?

(Technically speaking the rest of the function will be operating
on a deleted object. While the rest of the function might not
have any visible code, there may be destructors being run.)

Öö Tiib

unread,
Aug 15, 2022, 8:41:32 AM8/15/22
to
Can't find in standard but FAQ says it is,
<https://isocpp.org/wiki/faq/freestore-mgmt#delete-this>
Just that there are number of constraints and caveats that the slice of
code that is posted does not demonstrate taken into account.

JiiPee

unread,
Aug 24, 2022, 12:28:09 PM8/24/22
to
I use MFC quite a lot, believer me or not. In MFC they seem to use it
... the windows object deletes itself when the window is destroyed.

by the way, is this allowed? returning a value after the object is deleted:
int MyClass::Foo()
{
delete this;
return 6;
}

Bonita Montero

unread,
Aug 24, 2022, 11:59:18 PM8/24/22
to
0 new messages