-
-
Save nixiz/0055fefdc2b936b8f9ab6594b57a3abe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <chrono> | |
#include <functional> | |
#include <thread> | |
#include <memory> | |
typedef void (*long_async_function_cb)(void*, int); | |
static void c_long_async_function(void* context, | |
long_async_function_cb cb, | |
int in_param, | |
int sleep_msec = 300) { | |
std::thread([=] { | |
std::this_thread::sleep_for(std::chrono::milliseconds(sleep_msec)); | |
auto out_param = in_param * 2; | |
cb(context, out_param); | |
}).detach(); | |
} | |
class unsafe_service | |
: public std::enable_shared_from_this<unsafe_service> | |
{ | |
public: | |
unsafe_service() { p.reset(new int(1));} | |
~unsafe_service() {p.reset();} | |
std::shared_ptr<unsafe_service> getptr() { | |
return shared_from_this(); | |
} | |
void execute(); | |
void response(int out_param); | |
std::unique_ptr<int> p; | |
}; | |
struct async_callback_token { | |
std::weak_ptr<unsafe_service> caller; | |
}; | |
static inline void response_cb(void* context, int out_param) { | |
std::unique_ptr<async_callback_token> act_handle( | |
static_cast<async_callback_token*>(context)); | |
auto srv_ptr_weak = act_handle->caller; | |
if (auto srv_ptr = srv_ptr_weak.lock()) { | |
srv_ptr->response(out_param); | |
} | |
else { | |
std::cerr << "caller instance is deleted!!\n"; | |
} | |
} | |
void unsafe_service::execute() { | |
auto* context = new async_callback_token{ | |
this->weak_from_this() | |
}; | |
c_long_async_function((void*)context, response_cb, 300); | |
} | |
void unsafe_service::response(int out_param) | |
{ | |
std::cout << "received response: " << *p << "\n"; | |
} | |
int main() { | |
{ | |
auto s = std::make_shared<unsafe_service>(); | |
s->execute(); | |
// std::this_thread::sleep_for(std::chrono::milliseconds(500)); | |
} | |
std::this_thread::sleep_for(std::chrono::milliseconds(500)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
yukarıdaki kodu çalıştırmak için: https://godbolt.org/z/jfx5E73f4