Tuesday, December 15, 2009

When you want to make your function manage data in a thread-safe way.

When we want to make thread-specific memory area, we can use pthread_setspecific()/getspecfic() like below.

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

#define THREADNUM 30

struct ctx_t {
    pthread_t tid;
    int index;
} ctx[THREADNUM];

pthread_key_t t_key;

struct data_t {
    int var_a;
    char var_b;
};

void *thread_func(void *);
int sub_func(pthread_key_t);

int main()
{
    int i;
    void *res;

    pthread_key_create(&t_key, NULL);

    for (i = 0; i < THREADNUM; i++)
    {
        ctx[i].index = i;
        pthread_create(&ctx[i].tid, NULL, thread_func, (void *)&ctx[i]);
    }

    printf("Joining!\n");
    for (i = 0; i < THREADNUM; i++)
        pthread_join(ctx[i].tid, &res);

    pthread_key_delete(t_key);
}

void *thread_func(void *arg)
{
    int i;
    struct data_t *pdata;
    struct ctx_t *ctx;

    ctx = (struct ctx_t *)arg;

    pdata = (struct data_t *)malloc(sizeof(struct data_t));
    pdata->var_a = (ctx->index + 1) * 10;
    pdata->var_b = 0;
    pthread_setspecific(t_key, pdata);

    for (i = 0; i < 10; i++)
    {
        printf("Thread(%d) has value %d in its data space.\n",
            ctx->index, sub_func(t_key));
    }
    return NULL;
}

int sub_func(pthread_key_t key)
{
    struct data_t *pdata;
    pdata = (struct data_t *)pthread_getspecific(key);

    return pdata->var_a;
}

No comments:

Post a Comment