Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to unsubscribe? #51

Closed
GrossoMoreira opened this issue Jun 30, 2017 · 2 comments
Closed

How to unsubscribe? #51

GrossoMoreira opened this issue Jun 30, 2017 · 2 comments

Comments

@GrossoMoreira
Copy link

Hi,

The subscriber.cpp example shows how to make an infinite loop that receives messages, but how do I break out of that loop?

I'm running the subcriber in a separate thread, with a connection that is not being used for anything else.
Whenever the get_reply() function returns, it always returns 3 elements: {"message", channelname, content }. But how do I make it stop?

I tried the following in the main thread:
conn->run(command("UNSUBSCRIBE") << channelname);

That is, using the same connection that is being used by the subscriber thread. After this line of code is executed, the get_reply() function in the subscriber thread returns this: { "unsubscribe", channelname, "" }.

So, I found a way for the subcriber thread to unblock and know when to break out of the loop and return: it just needs to check if the first element of the reply is "message" or "unsubscribe".

However, now the call to the unsubscribe command in the main thread blocks forever! How am I supposed to do this then?

Thank you very much!

@luca3m
Copy link
Owner

luca3m commented Jul 4, 2017

You can try to use append instead of run on the main thread. It should work.

About your approach, I'm just unsure about the multi-thread safety of using the same connection from multiple threads, but for sure since the subscriber is blocked on get_reply there is now other way than using another thread, an alternative can be to add some sort of get_reply_with_timeout equivalent, so the subscriber has a way to unlock itself.

@GrossoMoreira
Copy link
Author

I tried both approaches and had no success.

  1. The approach with 'append' had no effect. I'm not sure how I could have done something wrong here.
  2. To implement the timeout, I added a method 'set_timeout' to the connection class that calls 'redisSetTimeout'. Using this method after creating the connection, the get_reply() function always returns {"", "", ""} before the timeout even elapses.

Maybe I did something wrong?

Anyway, I figured out another way to do it: I just send a PUBLISH command from some other thread to wake up the subscriber thread.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants