Created
February 14, 2017 21:47
-
-
Save michael-grunder/edb0a438a6e923c3cf375038be73c7c9 to your computer and use it in GitHub Desktop.
Hiredis BLPOP in a thread
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 <stdio.h> | |
#include <string.h> | |
#include <pthread.h> | |
#include <hiredis/hiredis.h> | |
void *popWorker(void *context) { | |
const char *channel = (char*)context; | |
struct timeval tv = {1, 0}; | |
redisContext *c; | |
redisReply *r; | |
c = redisConnectWithTimeout("localhost", 6379, tv); | |
if (!c || c->err) { | |
fprintf(stderr, "Can't connect to redis\n"); | |
return NULL; | |
} | |
while (1) { | |
r = redisCommand(c, "BLPOP %s 0", channel); | |
if (r == NULL || c->err) { | |
fprintf(stderr, "Error reading from list\n"); | |
return NULL; | |
} | |
if (r->type != REDIS_REPLY_ARRAY || r->elements < 2) { | |
fprintf(stderr, "Invalid BLPOP reply from Redis\n"); | |
return NULL; | |
} | |
if (!strcmp(r->element[1]->str, "exit")) { | |
printf("Received 'exit' message, shutting down...\n"); | |
return NULL; | |
} | |
printf("Redis: %s => %s\n", r->element[0]->str, r->element[1]->str); | |
freeReplyObject(r); | |
} | |
} | |
int main(void) { | |
pthread_t worker; | |
const char *channel = "testlist"; | |
/* Create our worker */ | |
if (pthread_create(&worker, NULL, popWorker, (void*)channel) != 0) { | |
fprintf(stderr, "Can't start thread\n"); | |
return 1; | |
} | |
/* Wait for it to finish */ | |
pthread_join(worker, NULL); | |
printf("All done...\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment