What is the use of privdata argument in redisAsyncCommand?

1.7k views Asked by At

The function definition provided in the source for redisAsyncCommand( ) is:

static int __redisAsyncCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, const char *cmd, size_t len) { ... }

What is the purpose of the void *privdata argument? In what cases would it be useful?

1

There are 1 answers

2
Igor On BEST ANSWER

As I understand by reading the code on gihub, the purpose of privdata is to send your callback some predefined data (which can be anything; that is why void* is used). In your callback (fn pointer to redisCallbackFn) you will recieve that privdata as parameter (for example look at cb->fn(ac,reply,cb->privdata); in func __redisRunCallback file async.c)

For example (simplified pseudo code for something similar) is bellow. In this example there are 3 successive calls to __redisAsyncCommandSimplified and only one handler (callback). In callback I have used privdata to determine behavior of callback. Your callback can also use that privdata data for something else (like parameter for another function call, logging, structure creation/population, etc)...

#include <stdio.h>
#include <string.h>

typedef void (*Callback)(int, void*);

int __redisAsyncCommandSimplified(Callback call, void* privdata) {
    call(1, privdata);
    return 1;
}

void myHandler(int status, void* privdata) {
    char* str = (char*)privdata;
    printf("%s = ", str);
    if (strcmp (str, "john") == 0) {
        printf("lennon");
    }
    else if (strcmp(str, "ringo") == 0) {
        printf("star");
    }
    else if (strcmp(str, "ringo") == 0) {
        printf("star");
    }
    else if (strcmp(str, "paul") == 0) { 
        printf("mccartney");
    }
    else if (strcmp(str, "george")) { 
        printf("harrison");
    }    
    else {
        printf("who?!?");
    }
    printf("\n");
}


int main()
{
  char c[20];
  strcpy(c, "john");
  __redisAsyncCommandSimplified(myHandler, c);
  strcpy(c, "paul");
  __redisAsyncCommandSimplified(myHandler, c);
  strcpy(c, "someone else");
  __redisAsyncCommandSimplified(myHandler, c);
  return 0;
}