Do I need to delete threads?

Hi guys, if I create a new array of threads using the new operator (so I can use a variable sized array) like this:

std::thread* foo = new std::thread[size];

do i need to delete it afterwards it like standard variables allocated of the heap? Thanks!

Cube777
Yes. Everything that is new'd must be delete'd or else it will leak memory.


Though rather than manually deleting, you can use a smart pointer or a container so the cleanup is automatic.
Why don't you use a vector of threads instead? Threads are move-constructible.
Thanks for the help! And I don't use vectors for this project because it has a huge amount of iterations and I found vector pushback to be very slow.. but thanks for the suggestion anyway!
I found vector pushback to be very slow
.reserve() needed amount of elements before other operations and push_back() will not be slower than manual array manipulation
Though move-construct with push_back() is possible, favour reserve() and construct in-place with emplace_back().

The performance would be measurably better than that with a C-style array of pointers to individually allocated thread objects (one dynamic allocation instead of many, no extra level of indirection and better memory locality).
Ok thanks I'll be sure to look into it! I don't have much experience with vectors and didn't know about .reserve(), I'm still pretty new to C++ :)
It is quite straightforward:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <thread>
#include <vector>
#include <chrono>

void foo( int secs, int id )
{
    std::this_thread::sleep_for( std::chrono::seconds(secs) ) ;
    std::cout << id << " - done\n" << std::flush ;
}

int main()
{
    std::size_t n = 10 ;
    std::vector<std::thread> threads ;
    threads.reserve(n) ; // reserve space for 'n' threads
    
    for( std::size_t i = 0 ; i < n ; ++i ) 
          threads.emplace_back( foo, i%3, i ) ; // ask vector to construct the thread in-place
    
    for( auto& t : threads ) t.join() ;
}

http://coliru.stacked-crooked.com/a/253a472fd4fd02a7
Topic archived. No new replies allowed.