Tuesday, August 13, 2013

Thread Specific Data Example

Here is the Example to using Thread Specific Data..
In this example I am using File pointer as the TSD,setting the value of the key and then getting the correspoding file pointer for the particular thread...
Each Thread creates its log file and writes its name in the file....
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
static pthread_key_t key;
void write_to_file(void *ptr)
{
    FILE *fp= (FILE*)pthread_getspecific(key);
    fprintf(fp,"%s",(char*)ptr);
        fclose(fp);
}
void* perform(void *ptr)
{
    FILE *fp;
    char *filename=malloc(strlen((char*)ptr)+8 );
    sprintf(filename,"%slog.log",(char*)ptr);
    fp=fopen(filename,"w");
    pthread_setspecific(key,fp);
    write_to_file(ptr);
}
int main()
{
    pthread_t thread[5];
    char *msg[]={"thread1","thread2","thread3","thread4","thread5"};
    int i;
    pthread_key_create(&key,NULL);
    for(i=0;i<5;i++)
    {
        pthread_create(&thread[i],NULL,perform,(void*)msg[i]);
        pthread_join(thread[i],NULL);
    }
    printf("Now main ends");
    return 0;
}

2 comments:

  1. Not a good example. The problem with this example is you're creating a closing 5 threads sequentially. You're not opening 5 threads up. Then doing your operations, then closing them down. It should still work, but it would be better if you open all your threads in a loop, and close them all in a separate loop.

    ReplyDelete

Feel free to comment......