User Tools

Site Tools


This is an old revision of the document!


Callback from thread. A sample/pattern

thr-cb.c
/*
 * Copyright 2004-2019 Oleg Borodin  <borodin@unix7.org>
 */
 
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
 
typedef struct req {
    void (*cb)(void*);
    void* rdata;
    int rsize;
} req_t;
 
 
void* handler(void* argv) {
    /* reinterpret args */
    req_t* m = (req_t*)argv;
 
    /* some work */
    char* res = (char*)malloc(1024);
    memcpy(res, m->rdata, m->rsize);
    strcat(res, "+world");
 
    /* call callback function */
    (*(m->cb))(res);
    return NULL;
}
 
void cb(void* data) {
    /* some work in callback */
    printf("msg: %s\n", (char*)data);
 
    /* free data memory */
    free((void*)data);
}
 
 
int main(int argc, char **argv) {
    /* create request */
    req_t m;
    m.rdata = "hello";
    m.rsize = strlen(m.rdata);
    m.cb = cb;
 
    pthread_t thread;
    pthread_create(&thread, NULL, handler, &m);
    pthread_join(thread, NULL);
 
    return 0;
}

request with dispatch by type of request

thr-dcb.c
/*
 * Copyright 2004-2019 Oleg Borodin  <borodin@unix7.org>
 */
 
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
 
#define REQ_CATD 1
#define REQ_ZERO 0
 
typedef struct req {
    void (*cb)(void*);
    int type;
    void* rdata;
    int rsize;
} req_t;
 
 
void* handler(void* argv) {
    /* reinterpret args */
    req_t* m = (req_t*)argv;
 
    /* dispatch request */
    switch (m->type) {
        case REQ_CATD: {
            /* some work */
            char* res = (char*)malloc(1024);
            memcpy(res, m->rdata, m->rsize);
            strcat(res, "+world");
 
            /* call callback function */
            (*(m->cb))(res);
            break;
        }
        case REQ_ZERO:
        default:
            /* nop */
            break;
    }
    return NULL;
}
 
void cb(void* data) {
    /* some work in callback */
    printf("msg: %s\n", (char*)data);
 
    /* free data memory */
    free((void*)data);
}
 
 
int main(int argc, char **argv) {
    /* create request */
    req_t m;
    m.type = REQ_CATD;
    m.rdata = "hello";
    m.rsize = strlen(m.rdata);
    m.cb = cb;
 
    pthread_t thread;
    pthread_create(&thread, NULL, handler, &m);
    pthread_join(thread, NULL);
 
    return 0;
}

out

$ ./thr-cb
msg: hello+world

First PagePrevious PageBack to overviewNext PageLast Page