C++ Singleton Threading problem
I have a C++ singleton that runs as a separate thread. This singleton is derived from a base class provided by a library and it overrides the method onLogon(...). The onLogon method is synchronous, it wants to know right away if we accept the logon attempt.
Problem is we need to pass the logon information via message to a security server. We can register a callback with the security server listener (a separate thread) to get the results of the logon authentication message we sent. My question is how do I block in the onLogon method such that I can have the thread woken up by the callback I've registered with the security server listener thread, and how can I 开发者_运维问答then access the response returned from the security server in a thread-safe way (ie, I need to be able to handle multiple concurrent logon requests).
I'm totally stumped.
Use an empty semaphore. After you send the credentials to the security server, take the semaphore. Since it will be empty it will block execution. Then have the callback function post to the semaphore. That will then resume execution on the original thread.
Since callbacks typically allow an anonymous value to be passed as a parameter, you can register a pointer to a data structure that can be filled with the response.
I ended up going with boost::promise and boost::unique_future. It's was perfect for what I needed.
http://www.boost.org/doc/libs/1_43_0/doc/html/thread/synchronization.html#thread.synchronization.futures
精彩评论