Zach
Zach

Reputation: 5895

How to use std::thread?

When I use std::thread like this:

func()
{
   std::thread(std::bind(&foo, this));
}

the thread object is allocated in stack and is destroyed when func() returns. So I try to use it like:

func()
{
   std::thread* threadPtr = new std::thread(std::bind(&foo, this));
}

Where should I delete threadPtr? And how can I create a thread that is initially suspended?

Upvotes: 3

Views: 23282

Answers (2)

James Adkison
James Adkison

Reputation: 9602

How to use std::thread?

It depends on what you're doing in the thread, but most likely you'll want to use join. It is also possible to use detach but care must be taken to make sure it doesn't use any resources that may be destroyed while its executing.

std::thread(std::bind(&foo, this));

This doesn't make any sense. You're binding (using bind is not necessary) a this pointer but &foo is not a pointer to a member function (which would look like &Foo::foo). Assuming you meant to use a pointer to a member function that would mean func is also a member function of the same class (i.e., since it has access to the this pointer) therefore the following code gives you an example of something you could do.

Example Code

#include <iostream>
#include <thread>

class Foo
{
public:
    Foo() = default;

    ~Foo()
    {
        if (mThread.joinable())
        {
            mThread.join();
        }
    }

    void foo()
    {
        std::cout << "Foo::foo\n";
    }

    void func()
    {
        if (mThread.joinable())
        {
            mThread.join();
        }

        // Creates the thread without using 'std::bind'
        mThread = std::thread(&Foo::foo, this);
    }

private:
    std::thread mThread;
};

int main()
{
    {
        Foo f;
        f.func();
        f.func();
    }

    return 0;
}

Example Output

Foo::foo
Foo::foo

Where should I delete threadPtr?

I wouldn't dynamically allocate the thread, but in the above example code you would delete it after joining.

how can I create a thread that is initially suspended?

C++ doesn't directly support this but you can use platform specific APIs with std::thread::native_handle. Note, if you wanted to block just once at the very start you could possibly achieve this with a synchronization primitive (e.g., block on a std::mutex before running the actual thread).

Upvotes: 8

zneak
zneak

Reputation: 138251

If you want the thread to run independently, you need to use the detach() method on the object. Otherwise, the thread destructor will terminate your program if the object is destroyed while the thread is still running.

Threads start running as soon as they are created. You cannot create a thread object in a suspended state. You can either store the arguments to create the thread instead of actually creating it (possibly using, for instance, std::function), or make it block on a mutex or a condition variable until you are ready to let it run.

Upvotes: 6

Related Questions