2 ms·
I'm not sure it works even if it's moveable because there's no guarantee it will make copy elision everywhere it's needed. One way I was thinking about it was
by shin_lao 15y ago
I'm not sure it works even if it's moveable because there's no guarantee it will make copy elision everywhere it's needed.
One way I was thinking about it was std::vector<std::shared_ptr<std::thread>>
Additionally, this sucks:
#define NUM_THREADS 10
In C++03 you can write
static const int num_threads = 10;
Which is much better.
And instead of:
for(int i=0;i<NUM_THREADS;i++){
t[i] = thread(call_from_thread,i);
}
Better use std::generate.
I may look like I'm nitpicking but I think it's paramount in a tutorial to have all details really, really right so that it may trigger other questions and go in depth about why things are better a way or the other.
- exDM69 15y ago>> I'm not sure it works even if it's moveable because there's no guarantee it will make copy elision everywhere it's needed. Of course it works, since std::thread is movable but non-copyable, std::vector<std::thread> will be movable but non-copyable too. So the compiler type checking will make sure it's not copied anywhere. This works like a charm (with GCC 4.7-ish from git): #include <thread> #include <vector> #include <iostream> #include <algorithm> int main() { std::vector<std::thread> threads; for(int i = 0 ; i < 10 ; ++i) threads.push_back(std::thread([=]() { std::cout << i << std::endl; })); std::for_each(threads.begin(), threads.end(), [](std::thread& thread) { thread.join(); }); } >> Better use std::generate. I used to nitpick about not using std::algorithms when they're available, but I grew out of it. I figured out that std::algos are very limited (esp. in c++98), and while you can use them to do stuff, it usually takes a significant amount of brainpower only to reformulate your problem to be suitable for std::algorithms. There are so many situations where a good old loop will produce more readable code faster, so why bother with the standard algorithms if they're not a perfect fit? Btw. has std::generate improved at all in C++11? It's one of the most limited algorithms in c++98.
- shin_lao 15y ago>> it usually takes a significant amount of brainpower only to reformulate your problem to be suitable for std::algorithms That's true, but the final result generally ends up with less bugs and better thought out algorithms. It forces you to think "what problem am I currently trying to solve?"