Skip to main content

Posts

Showing posts from April, 2014

Mutex variable using pthread in C programming

#include <stdio.h> #include <stdlib.h> #include <pthread.h> void *functionC(); pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int counter = 0; main() { int rc1, rc2; pthread_t thread1, thread2; /* Create independent threads each of which will execute functionC */ if( (rc1=pthread_create( &thread1, NULL, &functionC, NULL)) ) { printf("Thread creation failed: %d\n", rc1); } if( (rc2=pthread_create( &thread2, NULL, &functionC, NULL)) ) { printf("Thread creation failed: %d\n", rc2); } /* Wait till threads are complete before main continues. Unless we */ /* wait we run the risk of executing an exit which will terminate */ /* the process and all threads before the threads have completed. */ pthread_join( thread1, NULL); pthread_join( thread2, NULL); exit(0); } void *functionC() { pthread_mutex_lock( &mutex1 ); counter++; pri

Write a program of greeting using pthread in C programming

#include <stdio.h> #include <string.h> #include <sys/types.h> #include <pthread.h> #include <stdlib.h> #include <unistd.h> #define MAX_THREAD 1000 typedef struct { int id; int nproc; }parm; char message[100]; /* storage for message */ pthread_mutex_t msg_mutex = PTHREAD_MUTEX_INITIALIZER; int token = 0; void* greeting(void *arg) { parm *p = (parm *) arg; int id = p->id; int i; if (id != 0) { /* Create message */ while (1) { pthread_mutex_lock(&msg_mutex); if (token == 0) { sprintf(message, "Greetings from process %d!", id); token++; pthread_mutex_unlock(&msg_mutex); break; } pthread_mutex_unlock(&msg_mutex); sleep(1); } /* Use strlen+1 so that '\0' gets transmitted */ } else { /* my_rank == 0 */ for (i = 1; i < p->nproc; i++) { while (1) { pthread_mutex_lock(&msg_mutex); if (token == 1) { printf("%s\n", m

Write a program of Hello World using pthread in C programming

#include < pthread.h > #include < stdio.h > #include < stdlib.h > #define NUM_THREADS 5 void *PrintHello(void *threadid) { long tid; tid = (long)threadid; printf("Hello World! It's me, thread #%ld!\n", tid); pthread_exit(NULL); } int main(int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int rc; long t; for(t=0;t< NUM_THREADS;t++){ printf("In main: creating thread %ld\n", t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); if (rc){ printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } } /* Last thing that main() should do */ pthread_exit(NULL); } OUTPUT Compile & run(linux terminal): gcc -o Pthread_Hello_world pthread_hello_world.c -lpthread ./Pthread_Hello_world OUTPUT: In main: creating thread 0 In main: creating thread 1 Hello World! It's me, thread #0! In main: creating thread 2 Hello Wo