Question

I want to write a C++ program which starts 2 threads. The first thread periodically generates...

I want to write a C++ program which starts 2 threads.

The first thread periodically generates a random number and adds it to the total.

The second thread periodically generates a random number and subtracts it from the total.

The main thread periodically monitors the value of the total. if the total exceeds the maximum value, the program terminates and alerts the user that the maximum has been exceeded. If the total undercuts the minimus value, the program terminates and alerts the user that the minimum has been undercut.

Requirements:

1. The program should be configured at startup via a configuration file. Parameters that should be configurable are:

- minimum and maximum values for the random number generation

- minimum and maximum, values for the total

- period for addition

- period for subtraction

- period for monitoring

2. The program should follow object-oriented design practices.

3. Use only the standard template library classes in your design(i.e. no third party libraries such as boost).

0 0
Add a comment Improve this question Transcribed image text
Answer #1

/** add_thread() sub_thread() are thread functions to add and subtract from total which is a global variable.
* MAXTOT and MINTOT are upper and lower limits which if the total crosses the program will terminate
* lockTotal is the mutex to update total atomically
* main function starts the threads
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

#define MAXTOT 10000 //Maximum total allowed after which program terminates
#define MINTOT 100 //Minimum total allowed below which program terminates
int total=1000; //Global variable storing total

pthread_mutex_t lockTotal; //Mutex lock to update the total variable atomically

//Thread for adding to total
void *add_thread(void *arg)
{
    printf("Started add_thread()\n");
   while(1){
       printf("add_thread(): total - %d\n", total);
       pthread_mutex_lock(&lockTotal); // mutex lock
       if(total > MAXTOT || total < MINTOT)// check if total has moved beyond the lower or higher limit
           pthread_exit(NULL);
       total = total + rand(); // add ramdon number to total
       pthread_mutex_unlock(&lockTotal); // mutex unlock
   }  
}

//Thread for subtracting from total
void *sub_thread(void *arg)
{
    printf("Started sub_thread()\n");
   while(1){
       printf("sub_thread(): total - %d\n", total);
       pthread_mutex_lock(&lockTotal); // mutex lock
       if(total > MAXTOT || total < MINTOT) // check if total has moved beyond the lower or higher limit
           pthread_exit(NULL);
       total = total - rand(); // subtract ramdon number from total
       pthread_mutex_unlock(&lockTotal); // mutex unlock
   }
}

int main()
{

        pthread_t addthread, subthread;
        int ret;

       pthread_mutex_init(&lockTotal,0); //Initialize mutex
      
        printf("In main: creating threads\n");
        ret = pthread_create(&addthread, NULL, &add_thread, NULL);
        if(ret != 0) {
                printf("Error: pthread_create() for add failed\n");
                exit(EXIT_FAILURE);
        }
      
       ret = pthread_create(&subthread, NULL, &sub_thread, NULL);
        if(ret != 0) {
                printf("Error: pthread_create() for sub failed\n");
                exit(EXIT_FAILURE);
        }
      
       pthread_mutex_destroy(&lockTotal);
        pthread_exit(NULL);
}

Add a comment
Know the answer?
Add Answer to:
I want to write a C++ program which starts 2 threads. The first thread periodically generates...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need to creatre a C++ program that can modify the producer and consumer. My main...

    I need to creatre a C++ program that can modify the producer and consumer. My main programmig language is C++. Modify "Producer and Consumer Problem" from lecture note so that it can use all buffer space, not "buffersize – 1" as in the lecture note. This program should work as follows: 1. The user will run the program and will enter two numbers on the command line. Those numbers will be used for buffersize and counter limit. 2. The main...

  • Write a program in c++ that generates a 100 random numbers between 1 and 1000 and...

    Write a program in c++ that generates a 100 random numbers between 1 and 1000 and writes them to a data file called "randNum.dat". Then re-open the file, read the 100 numbers, print them to the screen, and find and print the minimum and maximum values. Specifications: If your output or input file fails to open correctly, print an error message that either states: Output file failed to open Input file failed to open depending on whether the output or...

  • in C++ please ELET 2300 Programming Assignment # 2 Write a program that generates an array...

    in C++ please ELET 2300 Programming Assignment # 2 Write a program that generates an array filled up with random positive integer number ranging from 15 to 20, and display it on the screen. After the creation and displaying of the array, the program displays the following: [P]osition [Reverse, [A]verage, (Search, [Q]uit Please select an option: Then, if the user selects: -P (lowercase or uppercase): the program displays the array elements position and value pairs for all member elements of...

  • 2. Write a C++ program, that generates a set of random integers and places them in...

    2. Write a C++ program, that generates a set of random integers and places them in an array. The number of values generated and their range are entered by the user. The program then continually prompts the user for one of the following character commands: a: display all the values I: display the values less than a given value g display the values greater than a given value e: display all odd values o: display all even values q: quit...

  • C++ code blocks Exercise#2: Quiz marks Write a program that generates quiz marks at random, between...

    C++ code blocks Exercise#2: Quiz marks Write a program that generates quiz marks at random, between O and 10 inclusive, for a number (less than 50) of Your program should display the marks, class average, and how many students score students decided by the user. above class average. Sample input/output: nter class size: 15 uiz marks: 8 9 9 1 7 5 5 10 1 07 7 5 8 6 e class average is: 5.87 students scored above average

  • I need Help PLZ. I can't solving this in C program Given is a C program count_primes.c, which is an array Generates 10000 six-digit random numbers and then determines the number of primes in that...

    I need Help PLZ. I can't solving this in C program Given is a C program count_primes.c, which is an array Generates 10000 six-digit random numbers and then determines the number of primes in that array. It also measures the time that elapses during the calculation and returns it to the console along with the number of primes it finds. (a) Rewrite the program so that N threads are used to count the primes in the array. Each thread is...

  • Lottery Game (15 Numbers). Design and implement a C++ program that generates 15 random non-repeating positive...

    Lottery Game (15 Numbers). Design and implement a C++ program that generates 15 random non-repeating positive integer numbers from 1 to 999 (lottery numbers) and takes a single input from the user and checks the input against the 15 lottery numbers. The user wins if her/his input matches one of the lottery numbers. Your implementation must have a level of modularity (using functions) Functions you need to implement: Define function initialize() that takes array lotterNumbers[] as a parameter and assigns...

  • Use only Include<iostream> Question 01: write a complete C++ program that should print the result of...

    Use only Include<iostream> Question 01: write a complete C++ program that should print the result of each of functions the following a. Function name: FindMinElement The function should take 3 integer values and returns the minimum the number. b. Function name: FindMaxElement The function should takes integer values and returns the maximum the number. C. Function name: FindAverage The function should ask the user to input double value for 10 times and it should returns the average Of those values....

  • Problem: You will write a program a C++ to compute some statistics based on monthly average...

    Problem: You will write a program a C++ to compute some statistics based on monthly average temperatures for a given month in each of the years 1901 to 2016. The data for the average August temperatures in the US has been downloaded from the Climate Change Knowledge Portal, and placed in a file named “tempAugData.txt”, available on the class website. The file contains a sequence of 116 values. The temperatures are in order, so that the first one is for...

  • C programming. Write the code described in the picture with given 2 example executions of the...

    C programming. Write the code described in the picture with given 2 example executions of the code, and they must match. AND YOU CANT USE if statements! Problem: Allow the user to enter a positive integer value to represent the seed value for the random number generator. Next, generate a random integer that represents a possible number of points that a student may earn in a given class (0 to a maximum of 1000 possible points). Calculate the corresponding letter...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT