user3196371
user3196371

Reputation: 149

Passing a shared_ptr or unique_ptr to _beginthreadex

I would like to know is this is possible. Create a shared_ptr or unique_ptr of TestClass type.

Then call _beginthreadex and pass it a static method of the class as the function to execute and the shared_ptr or unique_ptr created before as data. Like this:

shared_ptr<TestClass> p = make_shared<TestClass>(count, "test");
HANDLE hth1 = (HANDLE)_beginthreadex(NULL, 0, p->ThreadStart,p, 0, NULL);

I normally use this approach without smart pointers, I usually create a normal pointer of TestClass and pass a static method of the TestClass and the pointer itself as data, then inside the static method I cast it to (TestClass *) and run the member methods of the class etc, do the work and when the thread is done I delete the pointer. Something like this:

    TestClass * p = new TestClass(count, "test");
    HANDLE hth1 = (HANDLE)_beginthreadex(NULL, 0, p->ThreadStart,p, 0, NULL);

What I want to achieve is to make the smart pointer to delete the object automatically when the thread ends because the smart pointer would be out of scope.

When I do it the way I am describing it above the compiler shows this error:

"no suitable conversion function from "std::shared_ptr" to "void *" exists"

Upvotes: 0

Views: 1040

Answers (2)

Rafal Mielniczuk
Rafal Mielniczuk

Reputation: 1342

_beginthreadex looks like c function, and to achieve what you want, you need to invoke copy constructor (or move in case of unique_ptr) to transfer ownership, which is not possible in c.

You may consider using std::thread class which plays nice with the rest of std suite.

Assuming you want to run:

void ThreadStart(std::shared_ptr<TestClass> p);

You can fire that by

void ThreadStart(std::shared_ptr<TestClass> p)
{
    cout << p->count << " " << p->name << endl;
}

int main()
{
    shared_ptr<TestClass> p = make_shared<TestClass>(33, "test");
    std::thread thr(ThreadStart, p);
    thr.join();
}

In case of std::unique_ptr you need to std::move it to the thread function, so it will be actually deleted at the thread's end:

void ThreadStart(std::unique_ptr<TestClass> p);
...
unique_ptr<TestClass> p = make_unique<TestClass>(33, "test");
std::thread thr(ThreadStart, std::move(p));

Upvotes: 2

Praetorian
Praetorian

Reputation: 109289

Use shared_ptr::get or unique_ptr::get to get access to a pointer to the managed object.

shared_ptr<TestClass> p = make_shared<TestClass>(count, "test");
HANDLE hth1 = (HANDLE)_beginthreadex(NULL, 0, p->ThreadStart, p.get(), 0, NULL);

Upvotes: 0

Related Questions