Friday, September 16, 2011

Write a program in C to perform multithreading.

/* This code creates log files for each parameter provided at command line. */
/* Compilation : xlc -o thread thread.c -lpthread */
/* Execution : thread */

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

void *ProcessFile(void *arg)
{
char name[32];
char buffer[128];
printf(__FUNCTION__" is processing for argument : %s!\n", (char*)arg);
FILE *FPtr;
sprintf(name, "%s.%s", (char*)arg, "log");
sprintf(buffer, "%s", (char*)arg);
FPtr=fopen(name, "w+");
fprintf(FPtr, "%s", buffer);
fclose(FPtr);
printf("%s has been successfully created!\n", name);
pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
pthread_t threads[argc];
int status;
int i;
if (argc<2)
{
printf("Usage : %s <parameter(s)>\n", argv[0]);
exit(EXIT_FAILURE);
}
else
{
for(i=1; i<argc; i++)
{
printf(__FUNCTION__" : creating thread %d for %s!\n", i, argv[i]);
status=pthread_create(&threads[i], NULL, ProcessFile, (void *)argv[i]);
if (status)
{
printf("ERROR: return code from pthread_create() is %d\n", status);
exit(EXIT_FAILURE);
}
}
pthread_exit(NULL);
}
}

No comments :