Reputation: 249
What is the proper way to pass a pointer to 2 threads that each one of the threads runs another operation?
#include <chrono>
#include <iostream>
#include <vector>
#include <thread>
#include <random>
struct Unit {
Unit(uint64_t id_) :
id(id_),
v(1000000000)
{}
uint64_t id;
std::vector<int> v;
};
void operation1(Unit* unit) {
std::cout << "Hello operation1";
}
void operation2(Unit* unit) {
std::cout << "Hello operation2";
}
void operationMain() {
Unit* unit = new Unit(1);
std::thread at1(&operation1, unit);
std::thread at2(&operation2, unit);
at1.detach();
at2.detach();
}
int main123(int argc, char** argv)
{
std::thread t(&operationMain);
t.join();
return 0;
}
Here is my code, and I think I have a memory leak because 'unit' is passing to several operations in different threads.
Any suggestions?
Upvotes: 1
Views: 372
Reputation: 8579
My suggestion is to not use detach()
but use join()
or not share the object or create one of in (say) the at1
thread, detach()
it and create at2
the as a thread within that second thread and join in the at1
thread or allocated a shared_ptr<>
but shared ownership is way down the list as 'avoid where possible'.
detach()
means a thread executes independently and you cannot call join()
on a detached thread so you have no suitable point at which to cause the delete
of the dynamically allocated Unit
to take place in the calling thread.
It's not clear from the question why you've allocated shared resources and then called detach()
.
On my machine I get no output (even with a realistic size for the vector) because the main()
thread ends before the detach threads do anything meaningful.
This should work fine:
void operationMain() {
std::unique_ptr<Unit> unit (std::make_unique<Unit>(1));
std::thread at1(operation1, unit.get());
std::thread at2(operation2, unit.get());
at1.join();
at2.join();
//at1 and at2 have terminated and the unique_ptr destructor will delete the object (RAII).
}
Upvotes: 1