Destruction of boost::thread functor is later than with std::thread

Open
#380 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
35/100
Issue type
Bug
Clarity
Needs clarification
Activity status
Stale
Tech stack
cpp

Research direction

Start with the supplied main() and test() example, or reproduce it from the linked Wandbox, comparing std::thread and boost::thread behavior. The issue names no repository files or tests; done means determining whether the destruction difference is intentional and documenting or correcting it with evidence from the thread implementation.

Written by the indexing model from the issue text.

Description

It seems that boost::thread destroys its functor only when join is called. std::thread destroys its functor immediately after the functor returns. Is there a reason for this discrepancy?

Using RAII patterns this can lead to surprising deadlocks...

Example code:

#include <boost/thread/thread.hpp>

#include <cstdio>
#include <thread>
#include <utility>

struct foo {
    const char* name_ = nullptr;
    foo(const char* name) : name_(name) { printf("%s foo()\n", name); }
    foo(foo&& o) noexcept : name_(std::exchange(o.name_, nullptr)) {}
    foo(foo& o) = delete;
    ~foo() {
        if (name_) {
            printf("%s ~foo()\n", name_);
        }
    }
};

template <typename Thread>
void test(const char* name) {
    printf("%s starting\n", name);
    auto thread = Thread([&, f = foo(name)] { printf("%s done\n", name); });
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    printf("%s joining\n", name);
    thread.join();
    printf("%s joined\n\n", name);
}

int main() {
    test<std::thread>("std::thread");
    test<boost::thread>("boost::thread");
}

Output:

std::thread starting
std::thread foo()
std::thread done
std::thread ~foo()
std::thread joining
std::thread joined

boost::thread starting
boost::thread foo()
boost::thread done
boost::thread joining
boost::thread ~foo()
boost::thread joined

Wandbox

Dominant language
C++
Stars
213
Forks
171
PR merge metrics
No merged PRs in 30d

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from boostorg/thread

All issues in boostorg/thread

Similar issues

More C++ issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.