Write a multithreaded program that calculates various statistical values for a l
ID: 3757694 • Letter: W
Question
Write a multithreaded program that calculates various statistical values for a list of numbers. This program will be passed a series of numbers on the command and will then create three separate worker threads. One thread will determine the average of the numbers, the second will determine the maximum value, and the third will determine the minimum value. For example, suppose your program is passed the integers
90 81 78 95 79 72 85
The program will report
The average value is 82
The minimum value is 72
The maximum value is 95
The variables representing the average, minimum, and maximum values will be stored
globally. The worker threads will set these values, and the parent thread will output the values once the workers have exited.
Explanation / Answer
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
void* the_thread( void* );
void get_position();
struct position_t
{
int x;
int y;
};
namespace {
pthread_key_t position_key;
enum {
NUMBER_OF_THREADS = 2
};
}
int main(int argc, char **argv)
{
int result = pthread_key_create( &position_key, NULL );
printf( "pthread_key_create -- key: %u, result: %i ",
position_key, result );
pthread_t threads[NUMBER_OF_THREADS];
for (unsigned int i = 0; i < NUMBER_OF_THREADS; ++i )
{
position_t* position = new position_t();
position->x = ( 1 + i ) * 11;
position->y = ( 1 + i ) * 13;
result = pthread_create( &threads[i], NULL, the_thread, position );
}
sleep( 5 );
abort();
return 0;
}
void* the_thread( void* position )
{
int result = pthread_setspecific( position_key, position );
printf( "Thread: 0x%.8x, key: %u, value: 0x%.8x, result: %i ",
pthread_self(), position_key, position, result );
get_position();
return 0;
}
void get_position()
{
position_t* position =
reinterpret_cast< position_t* >( pthread_getspecific( position_key ) );
printf( "Thread: 0x%.8x, key: %u, position: 0x%.8x, x: %i, y: %i ",
pthread_self(), position_key, position, position->x, position->y );
while( true ) {};
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.