3/20/08

C Thread Example

This is a simple C Thread example. Don't forget, to compile use:

gcc -lpthread filename.c -o exename

This THREAD EXAMPLE in C is reads arg[1] as an integer (n) and starts n threads which print 100 numbers each. More specific if n is 5 then 5 threads will start and thread 1 will print from 0 - 99. thread 2 from 100 - 199.... thread i will print from i*100 - (i+1)*100.
As you see code is very simple. If you want to start threads in JAVA then read JAVA Thread example post.

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pthread.h>

#define MAX_THREAD 100

typedef struct {
int start,end;
} param;

void *count(void *arg) {
int i =0;
param *p=(param *)arg;
for(i =p->start ; i< p->end ; i++){
printf(" i = %d",i);
}
return (void*)(1);
}

int main(int argc, char* argv[]) {
int n,i;
pthread_t *threads;
param *p;

if (argc != 2) {
printf ("Usage: %s n\n",argv[0]);
printf ("\twhere n is no. of threads\n");
exit(1);
}

n=atoi(argv[1]);

if ((n < 1) || (n > MAX_THREAD)) {
printf ("arg[1] should be 1 - %d.\n",MAX_THREAD);
exit(1);
}

threads=(pthread_t *)malloc(n*sizeof(*threads));

p=(param *)malloc(sizeof(param)*n);
/* Assign args to a struct and start thread */
for (i=0; i<n; i++) {
p[i].start=i*100;
p[i].end=(i+1)*100;
pthread_create(&threads[i],NULL,count,(void *)(p+i));
}
printf("\nWait threads\n");
sleep(1);
/* Wait for all threads. */
int *x = malloc(sizeof(int));
for (i=0; i<n; i++) {
pthread_join(threads[i],(void*)x);
}
free(p);
exit(0);
}

1 comment:

Anonymous said...

thanks!!!