• Breaking News

    CS604 Assignment #1 Complete Solution -2018


    Code for CS604 Assignment (Fall 2018) 


    Code for the Program:
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <pthread.h>
    #define NUM_THREADS 3

    struct thread_data{
    int parentID,th_ID;
    char *name;
    char *detail;
    };
    struct thread_data thread_array[NUM_THREADS];
    void *MythreadFunc(void *value){
    int id,parentid;
    char *naam;
    char *kaam; 
    struct thread_data *my_data;
    sleep(1);
    my_data = (struct thread_data *)value;
    id = my_data -> th_ID;
    parentid = my_data -> parentID;
    naam = my_data -> name;
    kaam = my_data -> detail;
    printf("\nThread with ID :%ld ",pthread_self());
    printf(" and Parent ID: %d",parentid);
    printf(" created and started\n ");
    printf("%s\n",naam);
    printf("%s\n",kaam);
    pthread_exit(NULL);
    return NULL; 
    }
    int main(){
    pthread_t thread[NUM_THREADS];
    int process_id,rc;
    process_id = getpid();
    printf("\n\nCurrent Process ID :%d ",process_id);

    // Data of struct
    thread_array[0].name = "BC17000000";
    thread_array[0].detail = "XYZ";
    thread_array[0].parentID = process_id;
    thread_array[0].th_ID = pthread_self();
    thread_array[1].name = "CS604";
    thread_array[1].detail = "Operating System";
    thread_array[1].parentID = process_id;
    thread_array[1].th_ID = pthread_self();
    thread_array[2].name = "BSSE";
    thread_array[2].detail = "Virtual University of Pakistan";
    thread_array[2].parentID = process_id;
    thread_array[2].th_ID = pthread_self();
    // creating threads via loop
    for(int i = 0; i < NUM_THREADS; i++){
    rc = pthread_create(&thread[i],NULL,MythreadFunc,(void *)&thread_array[i]);
    if(rc){
    printf("ERROR: return code from pthread_create() is %d\n",rc);
    exit(-1);
    }

    }// joining the threads to main thread so it can wait until all created threads can execute before main thread 
    for(int i = 0; i < NUM_THREADS; i++)
    pthread_join(thread[i],NULL);
    printf("\n\nThreads are going to be terminated one by one\n");
    printf("\n All Threads exited safely...\n");
    pthread_exit(NULL);
    return EXIT_SUCCESS;

    }

    No comments