Posts

Showing posts from February, 2021

Write a code to pass a simple integer to each thread and measure time taken by each thread with out and with pthread_join. The calling thread uses a unique data structure for each thread, insuring that each thread's argument remains intact throughout the program.

Solution: 1) with our pthread_join //Write a code to pass a simple integer to each thread. The calling thread uses a unique //data structure for each thread, insuring that each thread's argument remains intact //throughout the program. // we try to display the massages based on user's imput through scanf // we try to find the time taken by each thread #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #define NUM_THREADS 8 // define total no of threds as global variable char *messages[NUM_THREADS]; // define the pointer globally to pass massage // pthread function void *PrintHello(void *threadid) { long taskid; sleep(1); taskid = (long) threadid; printf("Thread %d: %s\n", taskid, messages[taskid]); pthread_exit(NULL); } int main(int argc, char *argv[]) { clock_t tm1,tm2; double time_taken; pthread_t threads[NUM_THREADS]; // define pthread id long taskids[NUM_THREADS];        // define taskid int rc, t, NUM;...

print hello world using pthread through creating 5 threads.

#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); } ...

write simple code to create pthread and execute the code

/* Simple Pthreads example. */ #include <stdlib.h> #include <stdio.h> #include <pthread.h> void* ThreadFunc(void* arg); int main(int argc, char argv[]) { pthread_t idThread; puts("Let’s create a thread!"); pthread_create(&idThread, NULL, ThreadFunc, (void*) 5); pthread_join(idThread, NULL); } void* ThreadFunc(void* arg) { int i, n; /* Get the value of the argument passed in. */ n = (int) arg; /* Do stuff! */ for (i = 0; i < n; i++) printf("Loop %d: La la la!\n", i + 1); return NULL; } execute on teraminal gcc foo.c -o foo -Wall -lpthread ./foo   result Let’s create a thread! Loop 1: La la la! Loop 2: La la la! Loop 3: La la la! Loop 4: La la la! Loop 5: La la la!