Question

In: Computer Science

IN C LANGUAGE: Write a multi-threaded Linux program that synchronizes it's threads to write to a...

IN C LANGUAGE:

Write a multi-threaded Linux program that synchronizes it's threads to write to a file without the file becoming corrupted.

To do this, your program will create three threads which write strings to the same file. Each thread will randomly write a selection of strings to the file at random intervals. When finished, the file will contain all the strings written correctly to the file. You may use mutexes, semaphores, or a monitor your write on your own.

  • The first thread will write the following strings to the file: "eleven", "twelve", "thirteen", "fourteen", "fifteen".
  • The second thread will write the following strings to the file: "twenty one", twenty two", "twenty three", "twenty four", "twenty five".
  • The third thread will write the following strings to the file: "thirty one", thirty two", "thirty three", "thirty four", "thirty five".

Each string in the file should be on it's own line.   Each thread picks one of the strings at random and writes it to the file every 1 - 3 seconds, for a total of 20 lines.   

Use the sleep() system call to spread out the time in between writes.

To write to the file, use the open(), write(), and close() system calls.

So the file will start something like this:

eleven
thirty five
fifteen
twenty two
.
.
.

and continue for 60 total lines.

Keep in mind, the strings are randomly chosen and in random order.

Solutions

Expert Solution

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <pthread.h> 
#include <limits.h> 
#include <string.h>


pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

FILE *fptr;

int GetRandoms(int lower, int upper) 
{ 
    int num  = (rand() %  (upper - lower + 1)) + lower; ;
    return num;
} 


struct Node { 
    char data[100];
    struct Node* next; 
};

struct Node* CreateNode(char* data, struct Node* next)
{
    struct Node* n = (struct Node*)malloc(sizeof(struct Node));
    strcpy(n->data, data);
    n->next = next;
    return n;
}

void printList(struct Node* n) 
{ 
    while (n != NULL) { 
        printf("\n %s ", n->data); 
        n = n->next; 
    } 
}

void WriteFile(char* data)
{
    pthread_mutex_lock(&mutex);
    fputs(data, fptr);
    pthread_mutex_unlock(&mutex);
}

void *myThreadFun1(void *vargp) 
{ 
    int *myid = (int *)vargp; 
    struct Node* list = CreateNode("eleven\n",NULL);
    list->next = CreateNode("twelve\n",NULL);
    struct Node* endNode = list->next;
    endNode->next = CreateNode("thirteen\n",NULL);
    endNode = endNode->next;
    endNode->next = CreateNode("fourteen\n",NULL);
    endNode = endNode->next;
    endNode->next = CreateNode("fifteen\n",NULL);


    int nodeCount = 5;
    int nodeToWrite = 0;
    struct Node* writeNode;
    
    
    
    for(int i = 0 ; i < 20; i++)
    {
        sleep(GetRandoms(1,3)); 

        nodeToWrite = GetRandoms(1,nodeCount);

        printf("\nThread Id : %d\tGoing to write index %d ",*myid,nodeToWrite);

        if(nodeToWrite == 1)
        {
            writeNode = list;
        }
        else if (nodeToWrite == nodeCount)
        {
            writeNode = endNode->next;
        }
        else
        {
            struct Node* temp = list;

            for(int j = 2; j < nodeToWrite; j++)
            {
                temp = temp->next;
            }

            writeNode = temp->next;

            
        }
        
        printf("\nThread Id : %d\tWriting %s ",*myid,writeNode->data);
        WriteFile(writeNode->data);

    }

    return 0; 
} 

void *myThreadFun2(void *vargp) 
{ 
    int *myid = (int *)vargp; 
    struct Node* list = CreateNode("twenty one\n",NULL);
    list->next = CreateNode("twenty two\n",NULL);
    struct Node* endNode = list->next;
    endNode->next = CreateNode("twenty three\n",NULL);
    endNode = endNode->next;
    endNode->next = CreateNode("twenty four\n",NULL);
    endNode = endNode->next;
    endNode->next = CreateNode("twenty five\n",NULL);

    //printList(list);

    int nodeCount = 5;
    int nodeToWrite = 0;
    struct Node* writeNode;
    
    
    for(int i = 0 ; i < 20; i++)
    {
        sleep(GetRandoms(1,3)); 

        nodeToWrite = GetRandoms(1,nodeCount);

        printf("\nThread Id : %d\tGoing to write index %d ",*myid,nodeToWrite);

        if(nodeToWrite == 1)
        {
            writeNode = list;
        }
        else if (nodeToWrite == nodeCount)
        {
            writeNode = endNode->next;
        }
        else
        {
            struct Node* temp = list;

            for(int j = 2; j < nodeToWrite; j++)
            {
                temp = temp->next;
            }

            writeNode = temp->next;
            
        }
        //printList(list);
        
        printf("\nThread Id : %d\tWriting %s ",*myid,writeNode->data);
        WriteFile(writeNode->data);

    }

    return 0; 
} 

void *myThreadFun3(void *vargp) 
{ 
    int *myid = (int *)vargp; 
    struct Node* list = CreateNode("thirty one\n",NULL);
    list->next = CreateNode("thirty two\n",NULL);
    struct Node* endNode = list->next;
    endNode->next = CreateNode("thirty three\n",NULL);
    endNode = endNode->next;
    endNode->next = CreateNode("thirty four\n",NULL);
    endNode = endNode->next;
    endNode->next = CreateNode("thirty five\n",NULL);

    //printList(list);

    int nodeCount = 5;
    int nodeToWrite = 0;
    struct Node* writeNode;
    
    
    for(int i = 0 ; i < 20; i++)
    {
        sleep(GetRandoms(1,3)); 

        nodeToWrite = GetRandoms(1,nodeCount);

        printf("\nThread Id : %d\tGoing to write index %d ",*myid,nodeToWrite);

        if(nodeToWrite == 1)
        {
            writeNode = list;
        }
        else if (nodeToWrite == nodeCount)
        {
            writeNode = endNode->next;
        }
        else
        {
            struct Node* temp = list;

            for(int j = 2; j < nodeToWrite; j++)
            {
                temp = temp->next;
            }

            writeNode = temp->next;

            
        }
        //printList(list);
        
        printf("\nThread Id : %d\tWriting %s ",*myid,writeNode->data);
        WriteFile(writeNode->data);

    }

    return 0; 
} 



int main() 
{ 
    srand(time(0));
 
    fptr = fopen("output.txt","w+");

    if(fptr == NULL)
    {
        printf("\nError!");   
        exit(1);             
    }

        int i; 
        pthread_t tid[3]; 
 
    pthread_create(&tid[0], NULL, myThreadFun1, (void *)&tid[0]); 
    pthread_create(&tid[1], NULL, myThreadFun2, (void *)&tid[1]); 
    pthread_create(&tid[2], NULL, myThreadFun3, (void *)&tid[2]); 

    for (i = 0; i < 3; i++) 
        pthread_join(tid[i], NULL);
    fclose(fptr);

    printf("Exiting...");
        return 0; 
} 

I hope this would be helpfull for you. if you like the answer give thumb up. If you have any query feel free to ask in comment section.


Related Solutions

C Programming language problem I need to write a program which uses several threads (like 8...
C Programming language problem I need to write a program which uses several threads (like 8 threads for example) to sum up a number. The following program is using 1 thread but I need several threads to compile it. There was a hint saying that using multiple separate for loop and combining them will make a multi-threaded program. #include <stdio.h> #include <stdlib.h> #include <pthread.h> int sum; // this data is shared by the threads void *runner(void *param); // threads call...
Write a program (in C, or Java, or C++, or C#) that creates three new threads...
Write a program (in C, or Java, or C++, or C#) that creates three new threads (besides the already existing main thread) and synchronizes them in such a way that each thread displays it's thread id in turn for 5 iterations. The output of the program should look like this: Thread 1 - iteration no. 1 Thread 2 - iteration no. 1 Thread 3 - iteration no. 1 Thread 1 - iteration no. 2 Thread 2 - iteration no. 2...
Introduction Write in C++ at the Linux command line a program that is the same as...
Introduction Write in C++ at the Linux command line a program that is the same as the previous collection app project but now uses a class to store the items and also can save the items to a file that can be read back into the array by the user when the program is re-started. You can use your project 1 submission as a starting point or you can do something new as long as it meets the listed requirements....
use linux or c program. please provide the answer in details. Write a program that will...
use linux or c program. please provide the answer in details. Write a program that will simulate non - preemptive process scheduling algorithm: First Come – First Serve Your program should input the information necessary for the calculation of average turnaround time including: Time required for a job execution; Arrival time; The output of the program should include: starting and terminating time for each job, turnaround time for each job, average turnaround time. Step 1: generate the input data (totally...
please write in c using linux or unix Write a program that will simulate non -...
please write in c using linux or unix Write a program that will simulate non - preemptive process scheduling algorithm: First Come – First Serve Your program should input the information necessary for the calculation of average turnaround time including: Time required for a job execution; Arrival time; The output of the program should include: starting and terminating time for each job, turnaround time for each job, average turnaround time. Step 1: generate the input data (totally 10 jobs) and...
Please write in C using linux or unix. Write a program that will simulate non -...
Please write in C using linux or unix. Write a program that will simulate non - preemptive process scheduling algorithm: First Come – First Serve Your program should input the information necessary for the calculation of average turnaround time including: Time required for a job execution; Arrival time; The output of the program should include: starting and terminating time for each job, turnaround time for each job, average turnaround time. Step 1: generate the input data (totally 10 jobs) and...
Write a C program that creates 5 threads sends the thread index as an argument to...
Write a C program that creates 5 threads sends the thread index as an argument to the thread execution procedure/function. Also, the main process/thread joins the newly created threads sequentially one after the other. From the thread procedure print “I am a thread and my index is “ [print the correct index number]. From the main thread after the join print “I am the main thread and just completed joining thread index “ [print the correct index].
C program for copying data from one directory to another using multi threading for linux using...
C program for copying data from one directory to another using multi threading for linux using command line arrangement. Program will take two arguments: 1: Source 2: Destination it will copy all the files from source to destination recursively Deadline: 4 hours from now.
Write the following in C language for Arduino: Write a program that turns on the LED...
Write the following in C language for Arduino: Write a program that turns on the LED at 25%, 50%, 75%, 100%, and then 0% brightness with a one second delay in between each change. Remember you are going to need to use a PWM pin and use the "analogWrite" command. The maximum value for our Arduino R3 boards is 255 and you need five steps (25%, 50%, 75%, 100%, and 0%) so you will need to determine the values for...
Write a “C” program(Linux) that creates a pipe and forks a child process. The parent then...
Write a “C” program(Linux) that creates a pipe and forks a child process. The parent then sends the following message on his side of the pipe “I am your daddy! and my name is <pid-of the-parent-process>\n”, the child receives this message and prints it to its stdout verbatim. The parent then blocks reading on the pipe from the child. The child writes back to its parent through its side ofthe pipe stating “Daddy, my name is <pid-of-the-child>”. The parent then...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT