-2

I'm trying to learn multithreading in C++ using the std::thread library. I can't find if a thread should be declared on the stack, or the heap; I tried searching with google and the search of this site but couldn't get a specific answer as to which of the two to use, and why.

Can someone please explain to me what would be the best use of allocating threads?

Sotem
  • 79
  • 7
  • 2
    IMO both are possible and this makes little difference, as long as the lifetime of the thread object is long enough. It can also be a global or thread-local object. –  Aug 12 '18 at 21:24
  • On ubuntu 17.10, 64 bit, the sizeof(std::thread) is 8 bytes, small enough that its size does not affect your choice of where. Where (to instantiate it) is more an issue of life time control, and perhaps other issues. – 2785528 Aug 13 '18 at 01:05
  • A `std::thread` object is a lightweight handle to an thread of execution. It's not polymorphic so there is no need to access it through a pointer to base. You can create it wherever you like, on the stack or on the heap, just like most types in C++. It supports move semantics, so if you create a `std::thread` on the stack you can easily move it to a different `std::thread` object, to transfer ownership of the thread of execution. (N.B. If you're trying to learn about multithreading, there are much more important things to worry about than this.) – Jonathan Wakely Aug 14 '18 at 11:40

1 Answers1

3

If you know at compile time the number of objects (std::threads, in this case) that you need, then it is usually a good default choice to use an automatic variable (an array for multiple objects). Automatic objects are allocated on the stack.

An exception to this rule of thumb is a case where the objects are very large in relation to the size of the stack. Big objects need to be allocated dynamically. The size of std::thread on my system is 8 bytes. The exact size of object that need to be allocated dynamically is highly situational, but for vast majority of cases, 8 bytes is small enough (by significant margin) to be stored on the stack.

However, if you don't know at compile time how many objects you need, then you would need to resort to dynamic allocation. Typically by using a standard container (std::vector<std::thread> for example).

eerorika
  • 232,697
  • 12
  • 197
  • 326