#include <iostream>
#include <thread>
#include <functional>
#include <map>
class hoge {
public:
int num;
hoge(const hoge& rv)
: num(rv.num)
{
std::cout << "hoge(const hoge& rv) called" << std::endl;
}
hoge(int num)
: num(num)
{
std::cout << "hoge() called" << std::endl;
}
~hoge()
{
std::cout << "num: " << num << " ";
std::cout << "~hoge() called" << std::endl;
}
};
std::map<int, std::thread*> pool;
int counter = 0;
void doAsync(std::function<void (std::shared_ptr<hoge>)> callback)
{
int i = counter++;
std::thread *th = new std::thread([=]() {
std::this_thread::sleep_for(std::chrono::seconds(2));
callback(std::shared_ptr<hoge>(new hoge(i)));
pool[i]->detach();
delete pool[i];
pool.erase(i);
});
pool.insert(std::pair<int, std::thread*>(i, th));
}
void doAsync2(std::function<void (std::shared_ptr<hoge>)> callback)
{
counter++;
std::thread *th1 = new std::thread();
std::thread th = std::thread([=]() {
std::this_thread::sleep_for(std::chrono::seconds(2));
callback(std::shared_ptr<hoge>(new hoge(counter)));
th1->detach();
delete th1;
});
th1->swap(th);
}
int main()
{
doAsync2([](std::shared_ptr<hoge> phoge) {
std::cout << "callback called: " << phoge.get()->num << std::endl;
std::shared_ptr<hoge> phoge2 = phoge;
doAsync2([=](std::shared_ptr<hoge>num2) {
std::cout << "callback called2: " << phoge2.get()->num << std::endl;
std::cout << "callback called2: " << num2.get()->num << std::endl;
});
});
std::this_thread::sleep_for(std::chrono::seconds(10));
return 0;
}
Last active
August 29, 2015 14:02
-
-
Save satoshikumano/e82104300cd15e635fce to your computer and use it in GitHub Desktop.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment