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

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].
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 that uses file handling operations of C language. The Program should perform...
Write a C Program that uses file handling operations of C language. The Program should perform following operations: 1. The program should accept student names and students’ assignment marks from the user. 2. Values accepted from the user should get saved in a .csv file (.csv files are “comma separated value” files, that can be opened with spreadsheet applications like MS-Excel and also with a normal text editor like Notepad). You should be able to open and view this file...
C# Programming Language Write a C# program ( Console or GUI ) that prompts the user...
C# Programming Language Write a C# program ( Console or GUI ) that prompts the user to enter the three examinations ( test 1, test 2, and test 3), homework, and final project grades then calculate and display the overall grade along with a message, using the selection structure (if/else). The message is based on the following criteria: “Excellent” if the overall grade is 90 or more. “Good” if the overall grade is between 80 and 90 ( not including...
C LANGUAGE ONLY Write a C program to count the frequency of each element in an...
C LANGUAGE ONLY Write a C program to count the frequency of each element in an array. Enter the number of elements to be stored in the array: 3 Input 3 elements of the array: element [0]: 25 element [1]: 12 element [2]: 43 Expected output: The frequency of all elements of an array: 25 occurs 1 times 12 occurs 1 times 3 occurs 1 times
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT