SlideShare a Scribd company logo
1 of 30
20145-5SumII_CSC374-407_assign3.html
CSC 374/407: Computer Systems II: 2015 Summer II,
Assignment #3
Last modified 2015 August 6
Purpose:
To practice working with POSIX threads, mutexes and
conditions;
and to practice good pointer programming in
CAssignment:The "telephone" game (70 Points)Overview
We are going to simulate the children's game of "telephone".
In this game N (in our case, 10) children are in a circle.
The first one says something to the second.
The second one may or may not hear what the first one said
accurately but he/she passes what he/she thinks was said to the
third.
This continues until the message gets to the last child.
The program for our game has two classes.
The first one, Sentence holds the current state of a sentence.
It has been written for you, and all you have to do is use it.
The second one, MessageSystem holds mutexes, conditions
and sentence pointer buffers between each child.
You'll have to finish this one.
For this assignment you have to:
You have to fill in the mutex and condition portions of
MessageSystem.
Write the function void* child (void*) that the child threads
will run.
Finish main() to invoke and wait for the child threads.
Each child i will get the pointer to its sentence from i-1 and
will transmit it (imperfectly) to i.
Thus it needs to access two buffers: one at i-1 and the other
at i.
All buffers are protected by mutexes, so child i-1 and child i
don't step on each other's toes when trying to access the buffer
at i-1.
Before child i can get the sentence pointer from the buffer at
i-1 the sentence has to be there.
If it is not it should temporarily surrender the lock (if it
obtained it) and wait until the sentence becomes available.
AssignmentCut and paste the following/*-------------------------
-------------------------------------------------*
*---- ----*
*---- telephoneGame ----*
*---- ----*
*---- This program simulates the children's game of
"telephone", ----*
*---- where an original message mutates as it is imperfectly
----*
*---- transmited among children in a pairwise manner.
----*
*---- ----*
*---- It demonstrates Linux/Unix thread programming
using ----*
*---- pthread_mutex_t and pthread_cond_t.
----*
*---- ----*
*---- Compile with: ----*
*---- linux> g++ -lpthread telephoneGame.cpp -o
telephoneGame----*
*---- ----*
*---- ---- ---- ---- ---- ---- ---- ---- ---- ----*
*---- ----*
*---- Version 1.0 Joseph Phillips 2010
October 23 ----*
*---- ----*
*-------------------------------------------------------------------------
-*/
/*------------------------------------------------------------------------
--*
*---- ----*
*---- Includes and namespace designations:
----*
*---- ----*
*-------------------------------------------------------------------------
-*/
#include <cstdlib>
#include <iostream>
#include <string>
#include <pthread.h>
using namespace std;
/*------------------------------------------------------------------------
--*
*---- ----*
*---- Definitions of constants: ---
-*
*---- ----*
*-------------------------------------------------------------------------
-*/
/* PURPOSE: To tell the number of children among whom to
pass the message.
*/
const int NUM_CHILDREN = 10;
/* PURPOSE: To tell the number of terms in the sentence.
*/
const int NUM_WORDS_IN_SENTENCE = 9;
/* PURPOSE: To tell the number of possible mutations for
each term.
*/
const int NUM_CHOICES_PER_POSITION = 3;
/* PURPOSE: To tell the possible terms for each position in
the sentence.
*/
const string
words[NUM_WORDS_IN_SENTENCE][NUM_CHOICES_
PER_POSITION]
= { {"The","He","Wee"},
{"quick","slick","thick"},
{"brown","round","found"},
{"fox","box","locks"},
{"jumped","thumped","pumped"},
{"over","clover","white cliffs of Dover"},
{"the","be","three"},
{"lazy","hazy","A to Z"},
{"dog","frog","hog"}
};
/*------------------------------------------------------------------------
--*
*---- ----*
*---- Definitions of classes and their methods and
functions: ----*
*---- ----*
*-------------------------------------------------------------------------
-*/
/* PURPOSE: To represent the current state of a Sentence.
*/
class Sentence
{
int wordChoices[NUM_WORDS_IN_SENTENCE];
// Disallow copy-assignment
Sentence& operator=(const Sentence&);
public :
// PURPOSE: To initialize '*this' sentence to its default state.
No
// parameters. No return value.
Sentence()
{
for (int index = 0; index < NUM_WORDS_IN_SENTENCE;
index++)
wordChoices[index] = 0;
}
// PURPOSE: To make '*this' a copy of 'source'. No return
value.
Sentence(const Sentence& source)
{
for (int index = 0; index <
NUM_WORDS_IN_SENTENCE; index++)
wordChoices[index] = source.wordChoices[index];
}
// PURPOSE: To release the resources of '*this'. No
parameters. No
// return value.
~Sentence ()
{
}
// PURPOSE: To return the current word at position 'index'.
const string& getWord (int index) const
{
return(words[index][wordChoices[index]]);
}
// PURPOSE: To (potentially) mutate one term of '*this'
sentence. No
// parameters. No return value.
void imperfectlyTransmit ()
{
wordChoices[rand()%NUM_WORDS_IN_SENTENCE] =
rand()%NUM_CHOICES_PER_POSITION;
}
};
/* PURPOSE: To print the text of Sentence 'sentence' to output
stream 'os'
* and to return 'os'.
*/
ostream& operator<< (ostream& os, const Sentence&
sentence)
{
for (int index = 0; index < NUM_WORDS_IN_SENTENCE;
index++)
{
os << sentence.getWord(index);
os << ((index == (NUM_WORDS_IN_SENTENCE-1)) ? '.' : '
');
}
return(os);
}
/* PURPOSE: To hold the state of the messaging system,
including the
* mutexes, conditions and sentence buffers.
*/
class MessageSystem
{
// YOUR CODE HERE FOR AN ARRAY OF
NUM_CHILDREN+1 MUTEXES
// YOUR CODE HERE FOR AN ARRAY OF
NUM_CHILDREN+1 CONDITIONS
Sentence* sentenceArray[NUM_CHILDREN+1];
// Disallow copy-construction
MessageSystem (const MessageSystem&);
// Disallow copy-assignment
MessageSystem& operator=(const MessageSystem&);
public :
// PURPOSE: To initialize the array of mutexes, the array of
conditions
// and the array of sentence pointers to be NULL.
MessageSystem ()
{
for (int index = 0; index <= NUM_CHILDREN; index++)
{
// YOUR CODE HERE TO INITIALIZE MUTEX NUMBER
index
// YOUR CODE HERE TO INITIALIZE CONDITION
NUMBER index
sentenceArray[index] = NULL;
}
}
// PURPOSE: To destroy the mutexes in their array, to
destroy the conditions
// in their array, to delete() the sentence pointers in their
array. No
// parameters. No return value.
~MessageSystem ()
{
for (int index = 0; index <= NUM_CHILDREN; index++)
{
// YOUR CODE HERE TO DESTROY MUTEX NUMBER
index
// YOUR CODE HERE TO DESTROY CONDITION
NUMBER index
delete(sentenceArray[index]);
}
}
// PURPOSE: To return a *pointer* to the lock at position
'index'.
pthread_mutex_t* getLockPtr (int index)
{
return(/* YOUR CODE HERE TO RETURN A POINTER TO
index-th MUTEX */ NULL);
}
// PURPOSE: To return a *pointer* to the condition at
position 'index'.
pthread_cond_t* getCondPtr (int index)
{
return(/* YOUR CODE HERE TO RETURN A POINTER TO
index-th CONDITION */ NULL);
}
// PURPOSE: To "give away" (set equal to NULL) the pointer
to the sentence
// at position 'index'.
Sentence* giveSentencePtr (int index)
{
Sentence* ptr = sentenceArray[index];
sentenceArray[index] = NULL;
return(ptr);
}
// PURPOSE: To set the sentence pointer at position 'index'
equal to
// 'sentencePtr'. No return value.
void setSentencePtr (int index, Sentence*
sentencePtr)
{
sentenceArray[index] = sentencePtr;
}
// PURPOSE: To return 'true' if the sentence at position
'index' is ready
// to be transmitted.
bool isReady (int index) const
{
return(sentenceArray[index] != NULL);
}
};
/*------------------------------------------------------------------------
--*
*---- ----*
*---- Definitions of global variables: ---
-*
*---- ----*
*-------------------------------------------------------------------------
-*/
/* PURPOSE: To hold the global messaging system.
*/
MessageSystem messageSystem;
/*------------------------------------------------------------------------
--*
*---- ----*
*---- Definitions of global functions: ---
-*
*---- ----*
*-------------------------------------------------------------------------
-*/
/* PURPOSE: To get the necessary locks, get the sentence,
print it,
* transmit it (imperfectly), and unlock and signal the next
child.
*/
void* child(void* argPtr)
{
// I. Applicability validity check:
// II. Run for current child:
// II.A. Get 'index':
// YOUR CODE HERE
// II.B. Announce that this child is ready:
// YOUR CODE HERE
// II.C. Get both locks and wait until signaled (if need to):
if ( (rand() % 2) == 1)
{
// YOUR CODE HERE
}
else
{
// YOUR CODE HERE
}
// YOUR CODE HERE
// II.D. Get pointer to sentence, print it and transmit it:
// YOUR CODE HERE
// II.E. Signal next child that message is ready and unlock
their
// YOUR CODE HERE
// III. Finished:
}
/* PURPOSE: To play the telephone game. 'argc' tells how
many command line
* arguments there are. 'argv[]' points to each. Returns
'EXIT_SUCCESS'
* to OS.
*/
int main (int argc, const char* argv[])
{
// I. Applicability validity check:
// II. Play game:
// II.A. Seed random number generator:
int randNumSeed;
if (argc >= 2)
randNumSeed = strtol(argv[1],NULL,10);
else
{
string entry;
cout << "Random number seed? ";
getline(cin,entry);
randNumSeed = strtol(entry.c_str(),NULL,10);
}
srand(randNumSeed);
// II.B. Play game:
Sentencesentence;
int childIndex;
int indices[NUM_CHILDREN+1];
// YOUR CODE HERE FOR AN ARRAY OF
NUM_CHILDREN+1 THREADS
messageSystem.setSentencePtr(0,&sentence);
for (childIndex = NUM_CHILDREN; childIndex > 0;
childIndex--)
{
indices[childIndex] = childIndex;
// YOUR CODE HERE TO INITIALIZE THREAD NUMBER
childIndex
}
for (childIndex = 1; childIndex <= NUM_CHILDREN;
childIndex++)
{
// YOUR CODE HERE TO WAIT FOR THREAD NUMBER
childIndex
}
cout << "Finally we have: "" <<
*messageSystem.giveSentencePtr(10) << """
<< endl;
// III. Finished:
return(EXIT_SUCCESS);
}
Finish class MessageSystem
The class needs two more arrays: one of
NUM_CHILDREN+1 pthread-mutexes and another of
NUM_CHILDREN+1 pthread-conditions.
All the objects in both arrays should be initialized in the
constructor, destroyed in the destructor, and should have
pointers returned in getLockPtr() and getCondPtr().
Write void* child (void* argPtr)
It might be useful to define an integer variable index
corresponding to the integer pointed to by argPtr.
Please note that argPtr has type void* and therefore
does not know it points to an integer.
A simple cout statement should suffice here.
Time for mutexes!
See that if statement?
In the "then" part of it lock
messageSystem.getLockPtr(index) first and
messageSystem.getLockPtr(index-1) second.
In the "else" part of it lock
messageSystem.getLockPtr(index-1) first and
messageSystem.getLockPtr(index) second.
(We do this to try to convince ourselves that our
program is robust over the vagaries of timing.)
Then we cout.
Finally we loop while our incoming message is not yet
ready (method isReady(index-1)).
In this loop we should wait to be signaled.
Here we've got to get a Sentence* (method
giveSentencePtr(index-1)).
We print out what we got and call method
imperfectlyTransmit() on it (how do you run a method on an
object given a pointer to it?).
Finally we set the updated sentence with
setSentencePtr(index,yourSentencePtrVar)
We got both locks index-1 and index, and here we unlock them.
Further, we should signal that there's a Sentence pointer
in the buffer at index for child index+1.
Finish int main ()
We need an array of NUM_CHILDREN+1 pthreads.
This array will be initialized in the first loop, where all child
threads are to run your function child() and all are passed the
address of indices[childIndex].
The child threads are initialized in reverse order to show how
robust our solution is; our children are well-behaved and will
not throw a tantrum if made to wait.
In the second loop we wait for each thread to finish.
Sample output:[[email protected] Assign3]$ telephoneGame 1
Child 9 ready to start
Child 9 got all his/her locks
Child 9 surrendering lock waiting for signal
Child 8 ready to start
Child 8 got all his/her locks
Child 8 surrendering lock waiting for signal
Child 7 ready to start
Child 7 got all his/her locks
Child 7 surrendering lock waiting for signal
Child Child 106 ready to start
ready to start
Child 6 got all his/her locks
Child 6 surrendering lock waiting for signal
Child 5 ready to start
Child 5 got all his/her locks
Child 5 surrendering lock waiting for signal
Child 4 ready to start
Child 4 got all his/her locks
Child 4 surrendering lock waiting for signal
Child 3 ready to start
Child 3 got all his/her locks
Child 3 surrendering lock waiting for signal
Child 2 ready to start
Child 2 got all his/her locks
Child 2 surrendering lock waiting for signal
Child 1 ready to start
Child 1 got all his/her locks
Child 1 says "The quick brown fox jumped over the lazy dog."
Child 2 says "The quick brown fox jumped clover the lazy dog."
Child 3 says "The quick brown fox jumped clover the lazy dog."
Child 4 says "The quick brown fox jumped clover the lazy dog."
Child 5 says "The quick brown fox jumped clover the lazy dog."
Child 6 says "The quick brown fox jumped clover the hazy
dog."
Child 7 says "The quick brown fox jumped clover the hazy
hog."
Child 8 says "The quick brown fox jumped clover the hazy
hog."
Child 9 says "The quick brown fox jumped clover the hazy
hog."
Child 10 got all his/her locks
Child 10 says "The quick brown fox jumped clover the hazy
frog."
Finally we have: "The slick brown fox jumped clover the hazy
frog."
[[email protected] Assign3]$ telephoneGame 2
Child Child 10 ready to start9 ready to start
Child 10 got all his/her locks
Child 10 surrendering lock waiting for signal
Child 9 got all his/her locks
Child 9 surrendering lock waiting for signal
Child 8 ready to start
Child 8 got all his/her locks
Child 8 surrendering lock waiting for signal
Child 6 ready to start
Child 6 got all his/her locks
Child 6 surrendering lock waiting for signal
Child 7 ready to start
Child 5 ready to start
Child 5 got all his/her locks
Child 5 surrendering lock waiting for signal
Child 4 ready to start
Child 4 got all his/her locks
Child 4 surrendering lock waiting for signal
Child 3 ready to start
Child 3 got all his/her locks
Child 3 surrendering lock waiting for signal
Child 2 ready to start
Child 2 got all his/her locks
Child 2 surrendering lock waiting for signal
Child 1 ready to start
Child 1 got all his/her locks
Child 1 says "The quick brown fox jumped over the lazy dog."
Child 2 says "The quick brown fox jumped over the lazy dog."
Child 3 says "Wee quick brown fox jumped over the lazy dog."
Child 4 says "Wee quick brown fox jumped over the lazy dog."
Child 5 says "Wee quick brown fox jumped over the lazy dog."
Child 6 says "Wee quick brown locks jumped over the lazy
dog."
Child 7 got all his/her locks
Child 7 says "Wee quick brown locks jumped over the lazy
hog."
Child 8 says "Wee quick brown locks jumped over the lazy
hog."
Child 9 says "Wee slick brown locks jumped over the lazy hog."
Child 10 says "Wee slick brown locks jumped over the lazy
hog."
Finally we have: "The slick brown locks jumped over the lazy
hog."
[[email protected] Assign3]$ telephoneGame 3
Child 10 ready to start
Child 10 got all his/her locks
Child 10 surrendering lock waiting for signal
Child 9 ready to start
Child 9 got all his/her locks
Child 9 surrendering lock waiting for signal
Child 8 ready to start
Child 8 got all his/her locks
Child 8 surrendering lock waiting for signal
Child 7 ready to start
Child 7 got all his/her locks
Child 7 surrendering lock waiting for signal
Child 6 ready to start
Child 6 got all his/her locks
Child 6 surrendering lock waiting for signal
Child 5 ready to start
Child 5 got all his/her locks
Child 5 surrendering lock waiting for signal
Child 4 ready to start
Child 4 got all his/her locks
Child 4 surrendering lock waiting for signal
Child 3 ready to start
Child 3 got all his/her locks
Child 3 surrendering lock waiting for signal
Child 2 ready to start
Child 2 got all his/her locks
Child 2 surrendering lock waiting for signal
Child 1 ready to start
Child 1 got all his/her locks
Child 1 says "The quick brown fox jumped over the lazy dog."
Child 2 says "The quick brown fox thumped over the lazy dog."
Child 3 says "He quick brown fox thumped over the lazy dog."
Child 4 says "He quick brown fox jumped over the lazy dog."
Child 5 says "He quick brown fox jumped over be lazy dog."
Child 6 says "He quick brown fox jumped over be lazy dog."
Child 7 says "He quick brown fox jumped over be lazy dog."
Child 8 says "He quick brown fox jumped over be lazy dog."
Child 9 says "He quick brown fox pumped over be lazy dog."
Child 10 says "He quick found fox pumped over be lazy dog."
Finally we have: "He slick found fox pumped over be lazy dog."
[[email protected] Assign3]$ telephoneGame 4
Child Child Child 109 ready to start ready to start
Child 9 got all his/her locks
Child 9 surrendering lock waiting for signal
8 ready to start
Child 8 got all his/her locks
Child 8 surrendering lock waiting for signal
Child 7 ready to start
Child 7 got all his/her locks
Child 7 surrendering lock waiting for signal
Child 6 ready to start
Child 6 got all his/her locks
Child 6 surrendering lock waiting for signal
Child 5 ready to start
Child 5 got all his/her locks
Child 5 surrendering lock waiting for signal
Child 4 ready to start
Child 4 got all his/her locks
Child 4 surrendering lock waiting for signal
Child 1 ready to start
Child 1 got all his/her locks
Child 1 says "The quick brown fox jumped over the lazy dog."
Child 3 ready to start
Child 3 got all his/her locksChild
Child 3 surrendering lock waiting for signal
2 ready to start
Child 2 got all his/her locks
Child 2 says "The quick brown fox jumped white cliffs of Dover
the lazy dog."
Child 3 says "The quick brown fox pumped white cliffs of
Dover the lazy dog."
Child 4 says "The quick brown fox jumped white cliffs of Dover
the lazy dog."
Child 5 says "The slick brown fox jumped white cliffs of Dover
the lazy dog."
Child 6 says "The slick brown fox jumped white cliffs of Dover
three lazy dog."
Child 7 says "The slick brown fox jumped white cliffs of Dover
three lazy dog."
Child 8 says "The slick brown fox jumped white cliffs of Dover
the lazy dog."
Child 9 says "He slick brown fox jumped white cliffs of Dover
the lazy dog."
Child 10 got all his/her locks
Child 10 says "He slick brown fox jumped white cliffs of Dover
the lazy dog."
Finally we have: "He slick brown box jumped white cliffs of
Dover the lazy dog."
[[email protected] Assign3]$ telephoneGame 5
Child Child 9 ready to start10 ready to start
Child 9 got all his/her locks
Child 9 surrendering lock waiting for signal
Child 8 ready to start
Child 8 got all his/her locks
Child 8 surrendering lock waiting for signal
Child 6 ready to start
Child 6 got all his/her locks
Child 6 surrendering lock waiting for signal
Child 7 ready to start
Child 5 ready to start
Child 5 got all his/her locks
Child 5 surrendering lock waiting for signal
Child 4 ready to start
Child 4 got all his/her locks
Child 4 surrendering lock waiting for signal
Child 3 ready to start
Child 3 got all his/her locks
Child 3 surrendering lock waiting for signal
Child 2 ready to start
Child 2 got all his/her locks
Child 2 surrendering lock waiting for signal
Child 1 ready to start
Child 1 got all his/her locks
Child 1 says "The quick brown fox jumped over the lazy dog."
Child 2 says "Wee quick brown fox jumped over the lazy dog."
Child 3 says "The quick brown fox jumped over the lazy dog."
Child 4 says "The thick brown fox jumped over the lazy dog."
Child 5 says "The thick brown fox jumped over the lazy dog."
Child 6 says "The thick brown fox pumped over the lazy dog."
Child 7 got all his/her locks
Child 7 says "The thick brown fox pumped over the lazy frog."
Child 8 says "The thick brown fox pumped over the lazy frog."
Child 9 says "The thick brown locks pumped over the lazy
frog."
Child 10 got all his/her locks
Child 10 says "The thick brown locks thumped over the lazy
frog."
Finally we have: "The thick brown locks thumped clover the
lazy frog."
[[email protected] Assign3]$ telephoneGame 6
Child 9 ready to start
Child 9 got all his/her locks
Child 9 surrendering lock waiting for signal
Child 8 ready to start
Child 8 got all his/her locks
Child 8 surrendering lock waiting for signal
Child 7 ready to start
Child 7 got all his/her locks
Child 7 surrendering lock waiting for signal
Child 6 ready to start
Child 6 got all his/her locks
Child 6 surrendering lock waiting for signal
Child 5 ready to start
Child 5 got all his/her locks
Child 5 surrendering lock waiting for signal
Child 4 ready to start
Child 4 got all his/her locks
Child 4 surrendering lock waiting for signal
Child 3 ready to start
Child 3 got all his/her locks
Child 3 surrendering lock waiting for signal
Child 2 ready to start
Child 2 got all his/her locks
Child 2 surrendering lock waiting for signal
Child 1 ready to start
Child 1 got all his/her locks
Child 1 says "The quick brown fox jumped over the lazy dog."
Child 2 says "The quick brown fox pumped over the lazy dog."
Child 3 says "The quick brown fox pumped over the lazy dog."
Child 4 says "The quick brown fox pumped over the lazy frog."
Child 5 says "The quick brown fox pumped over the lazy frog."
Child 6 says "The quick brown fox pumped over the lazy frog."
Child 7 says "The quick brown fox pumped over the lazy frog."
Child 8 says "The quick brown fox pumped clover the lazy
frog."
Child 9 says "The quick brown locks pumped clover the lazy
frog."
Child 10 ready to start
Child 10 got all his/her locks
Child 10 says "The quick brown locks pumped clover the lazy
dog."
Finally we have: "The quick brown locks pumped over the lazy
dog."
[[email protected] Assign3]$
Useful knowledge:
Function
What it does
int pthread_create
(/* Pointer to a pthread_t object */
pthread_t* restrict threadPtr,
/* Pointer to optional object for properties of child */
const pthread_attr_t* restrict attr,
/* Name of function to run: void* fncName(void* ptr) */
void *(*fncName)(void*),
/* Ptr to object that is parameter to fncName() */
void *restrict arg
)
Makes a thread in the space pointed to by threadPtr
The thread run the function void* fncName(void* ) and
passes arg to it.
Just leave attr as NULL for a generic thread.
int pthread_join
(/* Which thread to wait for */
pthread_t thread,
/* Pointer to pointer to receive pointer
returned by exiting thread's function.
*/
void** valuePtrsPtr
)
Waits for thread thread to finish.
When it does valuePtr (the thing that valuePtrsPtr points
to) is set to the thread's function's returned pointer value or it is
ignored if valuePtr==NULL
int pthread_mutex_init
(/* Ptr to space for mutex */
pthread_mutex_t *restrict mutexPtr,
/* Type of mutex (just pass NULL) */
const pthread_mutexattr_t *restrict attr
);
Initializes lock object pointed to by mutexPtr.
Just use NULL for 2nd parameter.
int pthread_mutex_destroy
(/* Ptr to mutex to destroy *.
pthread_mutex_t *mutex
);
Releases resources taken by mutex pointed to by mutexPtr.
int pthread_mutex_lock
(/* Pointer to mutex to lock */
pthread_mutex_t *mutexPtr
);
Either
Gains lock and proceeds, or
Waits for lock to become available
int pthread_mutex_unlock
(/* Pointer to mutex to unlock */
pthread_mutex_t *mutexPtr
);
Releases lock.
int pthread_cond_init
(/* Pointer to space in which to make condition */
pthread_cond_t *restrict condPtr,
/* Type of condition (just pass NULL) */
const pthread_condattr_t *restrict attr
);
Creates a condition.
int pthread_cond_destroy
(/* Pointer to condition to destroy */
pthread_cond_t *condPtr
);
Destroys pointed to condition.
int pthread_cond_wait
(/* Pointer to condition on which to wait */
pthread_cond_t *restrict condPtr,
/* Pointer to mutex to surrender until receive signal */
pthread_mutex_t *restrict mutexPtr
);
Suspends thread until receives signal on condPtr.
While thread is suspended it surrenders lock on mutexPtr
int pthread_cond_signal
(/* Ptr to condition which is signaled */
pthread_cond_t *condPtr
);
Wakes up at least one thread waiting for signal on condPtr.
Good C String Programming (30 Points)
Below there's a C program that is a case study in bad string
programming in C.
Re-write it into a proper C program that uses the C string
library.
Please note: For the C program the character arrays are too
small,
so the program will not let you enter everything and it's
output will
be bad.
That's okay!
We're trying to prevent crashing programs and
buffer-overflow attacks!
/*------------------------------------------------------------------------
-*
*--- ---*
*--- memoryNoNos.c ---*
*--- ---*
*--- This program makes all kinds of mistakes with C
strings. ---*
*--- Fix them! If you choose to make fixed-length arrays make
them ---*
*--- no bigger than 'MAX_STRING'. 'MAX_STRING' is too
small for ---*
*--- most applications, and that is the point. We want to prove
---*
*--- that even if the strings are too small we are not subject to
---*
*--- buffer overflow attacks. ---*
*--- ---*
*--- ---- ---- ---- ---- ---- ---- ---- ---- ---*
*--- ---*
*--- Version 1.0 Joseph Phillips 2015 August 6 ---
*
*--- ---*
*-------------------------------------------------------------------------
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX_STRING 30
// PURPOSE: To replace the newline character (if present) in
the string
// pointed to by 'cPtr' with the null-character ('0'). No return
value.
//
// NOTE: Assumes that the string pointed to by 'cPtr' is '0'
terminated!
void removeNewline (char* cPtr
)
{
cPtr = strchr(cPtr,'n');
if (cPtr != NULL)
*cPtr = '0';
}
char* getName ()
{
char* name;
printf("Please enter your name: ");
gets(name);
removeNewline(name);
return(name);
}
void getIcecreamFlavor (char* icecreamFlavor)
{
printf("Please enter the last flavor of ice cream that you ate:
");
gets(icecreamFlavor);
removeNewline(icecreamFlavor);
}
char* getCakeFlavor ()
{
char* cakeFlavor;
printf("Please enter the last flavor of cake that you ate: ");
gets(cakeFlavor);
removeNewline(cakeFlavor);
return(cakeFlavor);
}
char* report (const char* name,
const char* icecreamFlavor,
const char* cakeFlavor
)
{
char toReturn[MAX_STRING];
if (icecreamFlavor == cakeFlavor)
sprintf(toReturn,"%s, you sure love
%s!n",name,icecreamFlavor);
else
sprintf(toReturn,"%s, change is good!n",name);
return(toReturn);
}
int main ()
{
char* name;
char* icecreamFlavor;
char* cakeFlavor;
name = getName();
getIcecreamFlavor(icecreamFlavor);
cakeFlavor = getCakeFlavor();
printf(report(name,icecreamFlavor,cakeFlavor));
return(EXIT_SUCCESS);
}
20145-5SumII_CSC374-407_assign3.htmlCSC 374407 Computer Sy.docx

More Related Content

Similar to 20145-5SumII_CSC374-407_assign3.htmlCSC 374407 Computer Sy.docx

Fill in the missing code for C++- Code from part B is below to make co.pdf
Fill in the missing code for C++- Code from part B is below to make co.pdfFill in the missing code for C++- Code from part B is below to make co.pdf
Fill in the missing code for C++- Code from part B is below to make co.pdfAKPLAYZONEKOTA255
 
CS117-S18-AlharbiMohammed-master.gitignore.class.ctxt..docx
CS117-S18-AlharbiMohammed-master.gitignore.class.ctxt..docxCS117-S18-AlharbiMohammed-master.gitignore.class.ctxt..docx
CS117-S18-AlharbiMohammed-master.gitignore.class.ctxt..docxannettsparrow
 
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docxAssg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docxfestockton
 
Lab Assignment 4 CSE330 Spring 2014 Skeleton Code for ex.docx
 Lab Assignment 4 CSE330 Spring 2014  Skeleton Code for ex.docx Lab Assignment 4 CSE330 Spring 2014  Skeleton Code for ex.docx
Lab Assignment 4 CSE330 Spring 2014 Skeleton Code for ex.docxMARRY7
 
computer notes - Inter process communication
computer notes - Inter process communicationcomputer notes - Inter process communication
computer notes - Inter process communicationecomputernotes
 
Implementing of classical synchronization problem by using semaphores
Implementing of classical synchronization problem by using semaphoresImplementing of classical synchronization problem by using semaphores
Implementing of classical synchronization problem by using semaphoresGowtham Reddy
 
C program that prompts user to enter two floating point t.pdf
  C program that prompts user to enter two floating point t.pdf  C program that prompts user to enter two floating point t.pdf
C program that prompts user to enter two floating point t.pdfaoneonlinestore1
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Lin Yo-An
 
assign4assign4_part1bonnie.c This is a file system ben.docx
assign4assign4_part1bonnie.c  This is a file system ben.docxassign4assign4_part1bonnie.c  This is a file system ben.docx
assign4assign4_part1bonnie.c This is a file system ben.docxfestockton
 
CC++ echo serverThis assignment is designed to introduce network .pdf
CC++ echo serverThis assignment is designed to introduce network .pdfCC++ echo serverThis assignment is designed to introduce network .pdf
CC++ echo serverThis assignment is designed to introduce network .pdfsecunderbadtirumalgi
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...ssuserd6b1fd
 
Modify the bouncing ball example demonstrated/tutorialoutlet
Modify the bouncing ball example demonstrated/tutorialoutletModify the bouncing ball example demonstrated/tutorialoutlet
Modify the bouncing ball example demonstrated/tutorialoutletCleasbyz
 
week3_srcDoWhileLoopFactorial.javaweek3_srcDoWhileLoopFactoria.docx
week3_srcDoWhileLoopFactorial.javaweek3_srcDoWhileLoopFactoria.docxweek3_srcDoWhileLoopFactorial.javaweek3_srcDoWhileLoopFactoria.docx
week3_srcDoWhileLoopFactorial.javaweek3_srcDoWhileLoopFactoria.docxalanfhall8953
 
Ir remote kit_blink.pde
Ir remote kit_blink.pdeIr remote kit_blink.pde
Ir remote kit_blink.pdeCore Pale
 
The following is the (incomplete) header file for the class Fracti.pdf
The following is the (incomplete) header file for the class Fracti.pdfThe following is the (incomplete) header file for the class Fracti.pdf
The following is the (incomplete) header file for the class Fracti.pdf4babies2010
 
The TCP/IP Stack in the Linux Kernel
The TCP/IP Stack in the Linux KernelThe TCP/IP Stack in the Linux Kernel
The TCP/IP Stack in the Linux KernelDivye Kapoor
 

Similar to 20145-5SumII_CSC374-407_assign3.htmlCSC 374407 Computer Sy.docx (20)

Sockets and Socket-Buffer
Sockets and Socket-BufferSockets and Socket-Buffer
Sockets and Socket-Buffer
 
Fill in the missing code for C++- Code from part B is below to make co.pdf
Fill in the missing code for C++- Code from part B is below to make co.pdfFill in the missing code for C++- Code from part B is below to make co.pdf
Fill in the missing code for C++- Code from part B is below to make co.pdf
 
C Assignment Help
C Assignment HelpC Assignment Help
C Assignment Help
 
CS117-S18-AlharbiMohammed-master.gitignore.class.ctxt..docx
CS117-S18-AlharbiMohammed-master.gitignore.class.ctxt..docxCS117-S18-AlharbiMohammed-master.gitignore.class.ctxt..docx
CS117-S18-AlharbiMohammed-master.gitignore.class.ctxt..docx
 
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docxAssg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
 
Lab Assignment 4 CSE330 Spring 2014 Skeleton Code for ex.docx
 Lab Assignment 4 CSE330 Spring 2014  Skeleton Code for ex.docx Lab Assignment 4 CSE330 Spring 2014  Skeleton Code for ex.docx
Lab Assignment 4 CSE330 Spring 2014 Skeleton Code for ex.docx
 
computer notes - Inter process communication
computer notes - Inter process communicationcomputer notes - Inter process communication
computer notes - Inter process communication
 
Implementing of classical synchronization problem by using semaphores
Implementing of classical synchronization problem by using semaphoresImplementing of classical synchronization problem by using semaphores
Implementing of classical synchronization problem by using semaphores
 
C program that prompts user to enter two floating point t.pdf
  C program that prompts user to enter two floating point t.pdf  C program that prompts user to enter two floating point t.pdf
C program that prompts user to enter two floating point t.pdf
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015
 
assign4assign4_part1bonnie.c This is a file system ben.docx
assign4assign4_part1bonnie.c  This is a file system ben.docxassign4assign4_part1bonnie.c  This is a file system ben.docx
assign4assign4_part1bonnie.c This is a file system ben.docx
 
CC++ echo serverThis assignment is designed to introduce network .pdf
CC++ echo serverThis assignment is designed to introduce network .pdfCC++ echo serverThis assignment is designed to introduce network .pdf
CC++ echo serverThis assignment is designed to introduce network .pdf
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
 
Modify the bouncing ball example demonstrated/tutorialoutlet
Modify the bouncing ball example demonstrated/tutorialoutletModify the bouncing ball example demonstrated/tutorialoutlet
Modify the bouncing ball example demonstrated/tutorialoutlet
 
week3_srcDoWhileLoopFactorial.javaweek3_srcDoWhileLoopFactoria.docx
week3_srcDoWhileLoopFactorial.javaweek3_srcDoWhileLoopFactoria.docxweek3_srcDoWhileLoopFactorial.javaweek3_srcDoWhileLoopFactoria.docx
week3_srcDoWhileLoopFactorial.javaweek3_srcDoWhileLoopFactoria.docx
 
Ir remote kit_blink.pde
Ir remote kit_blink.pdeIr remote kit_blink.pde
Ir remote kit_blink.pde
 
The following is the (incomplete) header file for the class Fracti.pdf
The following is the (incomplete) header file for the class Fracti.pdfThe following is the (incomplete) header file for the class Fracti.pdf
The following is the (incomplete) header file for the class Fracti.pdf
 
The TCP/IP Stack in the Linux Kernel
The TCP/IP Stack in the Linux KernelThe TCP/IP Stack in the Linux Kernel
The TCP/IP Stack in the Linux Kernel
 

More from eugeniadean34240

I need a 7 pg research essay on the following   Select a real o.docx
I need a 7 pg research essay on the following   Select a real o.docxI need a 7 pg research essay on the following   Select a real o.docx
I need a 7 pg research essay on the following   Select a real o.docxeugeniadean34240
 
I need a 4-5 APA formatted paper with references that is clearly wri.docx
I need a 4-5 APA formatted paper with references that is clearly wri.docxI need a 4-5 APA formatted paper with references that is clearly wri.docx
I need a 4-5 APA formatted paper with references that is clearly wri.docxeugeniadean34240
 
I need a 3 page research paper on Title  Addictive being youn.docx
I need a 3 page research paper on Title  Addictive being youn.docxI need a 3 page research paper on Title  Addictive being youn.docx
I need a 3 page research paper on Title  Addictive being youn.docxeugeniadean34240
 
I need a 3 page double-spaced 12-point paper on Immunotherapy. the i.docx
I need a 3 page double-spaced 12-point paper on Immunotherapy. the i.docxI need a 3 page double-spaced 12-point paper on Immunotherapy. the i.docx
I need a 3 page double-spaced 12-point paper on Immunotherapy. the i.docxeugeniadean34240
 
I need a 2500 word essay on the 1st Battalion 7th Cavalry Regiment. .docx
I need a 2500 word essay on the 1st Battalion 7th Cavalry Regiment. .docxI need a 2500 word essay on the 1st Battalion 7th Cavalry Regiment. .docx
I need a 2500 word essay on the 1st Battalion 7th Cavalry Regiment. .docxeugeniadean34240
 
I need a 200-word paper that answers the following questions:D.docx
I need a 200-word paper that answers the following questions:D.docxI need a 200-word paper that answers the following questions:D.docx
I need a 200-word paper that answers the following questions:D.docxeugeniadean34240
 
i need a 2 page essay on LA crimes as it pertains to Rape you will h.docx
i need a 2 page essay on LA crimes as it pertains to Rape you will h.docxi need a 2 page essay on LA crimes as it pertains to Rape you will h.docx
i need a 2 page essay on LA crimes as it pertains to Rape you will h.docxeugeniadean34240
 
I need a 1 page professional bio. My cover letter and resume i.docx
I need a 1 page professional bio. My cover letter and resume i.docxI need a 1 page professional bio. My cover letter and resume i.docx
I need a 1 page professional bio. My cover letter and resume i.docxeugeniadean34240
 
I need 100 words response for this two discussion forum1 discu.docx
I need 100 words response for this two discussion forum1 discu.docxI need 100 words response for this two discussion forum1 discu.docx
I need 100 words response for this two discussion forum1 discu.docxeugeniadean34240
 
I need 200 words response for each discussion post.Guided Respon.docx
I need 200 words response for each discussion post.Guided Respon.docxI need 200 words response for each discussion post.Guided Respon.docx
I need 200 words response for each discussion post.Guided Respon.docxeugeniadean34240
 
I need 3 pages discussion for an intersection (Attached image).docx
I need 3 pages discussion for an intersection (Attached image).docxI need 3 pages discussion for an intersection (Attached image).docx
I need 3 pages discussion for an intersection (Attached image).docxeugeniadean34240
 
I need 1page write up on Hypothesis & Methods Proposal,Due on .docx
I need 1page write up on Hypothesis & Methods Proposal,Due on .docxI need 1page write up on Hypothesis & Methods Proposal,Due on .docx
I need 1page write up on Hypothesis & Methods Proposal,Due on .docxeugeniadean34240
 
I need 2-3 pages written about the sieve of Eratosthenes. Starti.docx
I need 2-3 pages written about the sieve of Eratosthenes. Starti.docxI need 2-3 pages written about the sieve of Eratosthenes. Starti.docx
I need 2-3 pages written about the sieve of Eratosthenes. Starti.docxeugeniadean34240
 
I need 120 words for each question. Please ensure to post individual.docx
I need 120 words for each question. Please ensure to post individual.docxI need 120 words for each question. Please ensure to post individual.docx
I need 120 words for each question. Please ensure to post individual.docxeugeniadean34240
 
I need 10-12 slides Presentation with detailed speaker notes. Instru.docx
I need 10-12 slides Presentation with detailed speaker notes. Instru.docxI need 10-12 slides Presentation with detailed speaker notes. Instru.docx
I need 10-12 slides Presentation with detailed speaker notes. Instru.docxeugeniadean34240
 
I N N O V A T I O N N E T W O R K , I N C . www.innone.docx
I N N O V A T I O N  N E T W O R K ,  I N C .   www.innone.docxI N N O V A T I O N  N E T W O R K ,  I N C .   www.innone.docx
I N N O V A T I O N N E T W O R K , I N C . www.innone.docxeugeniadean34240
 
I like to tie my learning to Biblical Principles. On Virtuous Le.docx
I like to tie my learning to Biblical Principles. On Virtuous Le.docxI like to tie my learning to Biblical Principles. On Virtuous Le.docx
I like to tie my learning to Biblical Principles. On Virtuous Le.docxeugeniadean34240
 
I just want one paragraph.!!C.W.Mills described ‘sociological im.docx
I just want one paragraph.!!C.W.Mills described ‘sociological im.docxI just want one paragraph.!!C.W.Mills described ‘sociological im.docx
I just want one paragraph.!!C.W.Mills described ‘sociological im.docxeugeniadean34240
 
i just need serious help answering the question. I have answered mos.docx
i just need serious help answering the question. I have answered mos.docxi just need serious help answering the question. I have answered mos.docx
i just need serious help answering the question. I have answered mos.docxeugeniadean34240
 
I Headnotes and indexes are copyrighted and may not be duplica.docx
I Headnotes and indexes are copyrighted and may not be duplica.docxI Headnotes and indexes are copyrighted and may not be duplica.docx
I Headnotes and indexes are copyrighted and may not be duplica.docxeugeniadean34240
 

More from eugeniadean34240 (20)

I need a 7 pg research essay on the following   Select a real o.docx
I need a 7 pg research essay on the following   Select a real o.docxI need a 7 pg research essay on the following   Select a real o.docx
I need a 7 pg research essay on the following   Select a real o.docx
 
I need a 4-5 APA formatted paper with references that is clearly wri.docx
I need a 4-5 APA formatted paper with references that is clearly wri.docxI need a 4-5 APA formatted paper with references that is clearly wri.docx
I need a 4-5 APA formatted paper with references that is clearly wri.docx
 
I need a 3 page research paper on Title  Addictive being youn.docx
I need a 3 page research paper on Title  Addictive being youn.docxI need a 3 page research paper on Title  Addictive being youn.docx
I need a 3 page research paper on Title  Addictive being youn.docx
 
I need a 3 page double-spaced 12-point paper on Immunotherapy. the i.docx
I need a 3 page double-spaced 12-point paper on Immunotherapy. the i.docxI need a 3 page double-spaced 12-point paper on Immunotherapy. the i.docx
I need a 3 page double-spaced 12-point paper on Immunotherapy. the i.docx
 
I need a 2500 word essay on the 1st Battalion 7th Cavalry Regiment. .docx
I need a 2500 word essay on the 1st Battalion 7th Cavalry Regiment. .docxI need a 2500 word essay on the 1st Battalion 7th Cavalry Regiment. .docx
I need a 2500 word essay on the 1st Battalion 7th Cavalry Regiment. .docx
 
I need a 200-word paper that answers the following questions:D.docx
I need a 200-word paper that answers the following questions:D.docxI need a 200-word paper that answers the following questions:D.docx
I need a 200-word paper that answers the following questions:D.docx
 
i need a 2 page essay on LA crimes as it pertains to Rape you will h.docx
i need a 2 page essay on LA crimes as it pertains to Rape you will h.docxi need a 2 page essay on LA crimes as it pertains to Rape you will h.docx
i need a 2 page essay on LA crimes as it pertains to Rape you will h.docx
 
I need a 1 page professional bio. My cover letter and resume i.docx
I need a 1 page professional bio. My cover letter and resume i.docxI need a 1 page professional bio. My cover letter and resume i.docx
I need a 1 page professional bio. My cover letter and resume i.docx
 
I need 100 words response for this two discussion forum1 discu.docx
I need 100 words response for this two discussion forum1 discu.docxI need 100 words response for this two discussion forum1 discu.docx
I need 100 words response for this two discussion forum1 discu.docx
 
I need 200 words response for each discussion post.Guided Respon.docx
I need 200 words response for each discussion post.Guided Respon.docxI need 200 words response for each discussion post.Guided Respon.docx
I need 200 words response for each discussion post.Guided Respon.docx
 
I need 3 pages discussion for an intersection (Attached image).docx
I need 3 pages discussion for an intersection (Attached image).docxI need 3 pages discussion for an intersection (Attached image).docx
I need 3 pages discussion for an intersection (Attached image).docx
 
I need 1page write up on Hypothesis & Methods Proposal,Due on .docx
I need 1page write up on Hypothesis & Methods Proposal,Due on .docxI need 1page write up on Hypothesis & Methods Proposal,Due on .docx
I need 1page write up on Hypothesis & Methods Proposal,Due on .docx
 
I need 2-3 pages written about the sieve of Eratosthenes. Starti.docx
I need 2-3 pages written about the sieve of Eratosthenes. Starti.docxI need 2-3 pages written about the sieve of Eratosthenes. Starti.docx
I need 2-3 pages written about the sieve of Eratosthenes. Starti.docx
 
I need 120 words for each question. Please ensure to post individual.docx
I need 120 words for each question. Please ensure to post individual.docxI need 120 words for each question. Please ensure to post individual.docx
I need 120 words for each question. Please ensure to post individual.docx
 
I need 10-12 slides Presentation with detailed speaker notes. Instru.docx
I need 10-12 slides Presentation with detailed speaker notes. Instru.docxI need 10-12 slides Presentation with detailed speaker notes. Instru.docx
I need 10-12 slides Presentation with detailed speaker notes. Instru.docx
 
I N N O V A T I O N N E T W O R K , I N C . www.innone.docx
I N N O V A T I O N  N E T W O R K ,  I N C .   www.innone.docxI N N O V A T I O N  N E T W O R K ,  I N C .   www.innone.docx
I N N O V A T I O N N E T W O R K , I N C . www.innone.docx
 
I like to tie my learning to Biblical Principles. On Virtuous Le.docx
I like to tie my learning to Biblical Principles. On Virtuous Le.docxI like to tie my learning to Biblical Principles. On Virtuous Le.docx
I like to tie my learning to Biblical Principles. On Virtuous Le.docx
 
I just want one paragraph.!!C.W.Mills described ‘sociological im.docx
I just want one paragraph.!!C.W.Mills described ‘sociological im.docxI just want one paragraph.!!C.W.Mills described ‘sociological im.docx
I just want one paragraph.!!C.W.Mills described ‘sociological im.docx
 
i just need serious help answering the question. I have answered mos.docx
i just need serious help answering the question. I have answered mos.docxi just need serious help answering the question. I have answered mos.docx
i just need serious help answering the question. I have answered mos.docx
 
I Headnotes and indexes are copyrighted and may not be duplica.docx
I Headnotes and indexes are copyrighted and may not be duplica.docxI Headnotes and indexes are copyrighted and may not be duplica.docx
I Headnotes and indexes are copyrighted and may not be duplica.docx
 

Recently uploaded

How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonhttgc7rh9c
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
What is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxWhat is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxCeline George
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfPondicherry University
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfNirmal Dwivedi
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxakanksha16arora
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptxJoelynRubio1
 
Economic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food AdditivesEconomic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food AdditivesSHIVANANDaRV
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of PlayPooky Knightsmith
 

Recently uploaded (20)

How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
What is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxWhat is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptx
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
Economic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food AdditivesEconomic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food Additives
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 

20145-5SumII_CSC374-407_assign3.htmlCSC 374407 Computer Sy.docx

  • 1. 20145-5SumII_CSC374-407_assign3.html CSC 374/407: Computer Systems II: 2015 Summer II, Assignment #3 Last modified 2015 August 6 Purpose: To practice working with POSIX threads, mutexes and conditions; and to practice good pointer programming in CAssignment:The "telephone" game (70 Points)Overview We are going to simulate the children's game of "telephone". In this game N (in our case, 10) children are in a circle. The first one says something to the second. The second one may or may not hear what the first one said accurately but he/she passes what he/she thinks was said to the third. This continues until the message gets to the last child. The program for our game has two classes. The first one, Sentence holds the current state of a sentence. It has been written for you, and all you have to do is use it. The second one, MessageSystem holds mutexes, conditions and sentence pointer buffers between each child. You'll have to finish this one. For this assignment you have to:
  • 2. You have to fill in the mutex and condition portions of MessageSystem. Write the function void* child (void*) that the child threads will run. Finish main() to invoke and wait for the child threads. Each child i will get the pointer to its sentence from i-1 and will transmit it (imperfectly) to i. Thus it needs to access two buffers: one at i-1 and the other at i. All buffers are protected by mutexes, so child i-1 and child i don't step on each other's toes when trying to access the buffer at i-1. Before child i can get the sentence pointer from the buffer at i-1 the sentence has to be there. If it is not it should temporarily surrender the lock (if it obtained it) and wait until the sentence becomes available. AssignmentCut and paste the following/*------------------------- -------------------------------------------------* *---- ----* *---- telephoneGame ----* *---- ----* *---- This program simulates the children's game of "telephone", ----* *---- where an original message mutates as it is imperfectly ----* *---- transmited among children in a pairwise manner. ----* *---- ----* *---- It demonstrates Linux/Unix thread programming using ----* *---- pthread_mutex_t and pthread_cond_t. ----*
  • 3. *---- ----* *---- Compile with: ----* *---- linux> g++ -lpthread telephoneGame.cpp -o telephoneGame----* *---- ----* *---- ---- ---- ---- ---- ---- ---- ---- ---- ----* *---- ----* *---- Version 1.0 Joseph Phillips 2010 October 23 ----* *---- ----* *------------------------------------------------------------------------- -*/ /*------------------------------------------------------------------------ --* *---- ----* *---- Includes and namespace designations: ----* *---- ----* *------------------------------------------------------------------------- -*/ #include <cstdlib> #include <iostream> #include <string> #include <pthread.h> using namespace std; /*------------------------------------------------------------------------ --* *---- ----*
  • 4. *---- Definitions of constants: --- -* *---- ----* *------------------------------------------------------------------------- -*/ /* PURPOSE: To tell the number of children among whom to pass the message. */ const int NUM_CHILDREN = 10; /* PURPOSE: To tell the number of terms in the sentence. */ const int NUM_WORDS_IN_SENTENCE = 9; /* PURPOSE: To tell the number of possible mutations for each term. */ const int NUM_CHOICES_PER_POSITION = 3; /* PURPOSE: To tell the possible terms for each position in the sentence. */ const string words[NUM_WORDS_IN_SENTENCE][NUM_CHOICES_ PER_POSITION] = { {"The","He","Wee"}, {"quick","slick","thick"}, {"brown","round","found"}, {"fox","box","locks"},
  • 5. {"jumped","thumped","pumped"}, {"over","clover","white cliffs of Dover"}, {"the","be","three"}, {"lazy","hazy","A to Z"}, {"dog","frog","hog"} }; /*------------------------------------------------------------------------ --* *---- ----* *---- Definitions of classes and their methods and functions: ----* *---- ----* *------------------------------------------------------------------------- -*/ /* PURPOSE: To represent the current state of a Sentence. */ class Sentence { int wordChoices[NUM_WORDS_IN_SENTENCE]; // Disallow copy-assignment Sentence& operator=(const Sentence&); public : // PURPOSE: To initialize '*this' sentence to its default state. No // parameters. No return value. Sentence() { for (int index = 0; index < NUM_WORDS_IN_SENTENCE;
  • 6. index++) wordChoices[index] = 0; } // PURPOSE: To make '*this' a copy of 'source'. No return value. Sentence(const Sentence& source) { for (int index = 0; index < NUM_WORDS_IN_SENTENCE; index++) wordChoices[index] = source.wordChoices[index]; } // PURPOSE: To release the resources of '*this'. No parameters. No // return value. ~Sentence () { } // PURPOSE: To return the current word at position 'index'. const string& getWord (int index) const { return(words[index][wordChoices[index]]); } // PURPOSE: To (potentially) mutate one term of '*this' sentence. No // parameters. No return value. void imperfectlyTransmit () { wordChoices[rand()%NUM_WORDS_IN_SENTENCE] = rand()%NUM_CHOICES_PER_POSITION; } };
  • 7. /* PURPOSE: To print the text of Sentence 'sentence' to output stream 'os' * and to return 'os'. */ ostream& operator<< (ostream& os, const Sentence& sentence) { for (int index = 0; index < NUM_WORDS_IN_SENTENCE; index++) { os << sentence.getWord(index); os << ((index == (NUM_WORDS_IN_SENTENCE-1)) ? '.' : ' '); } return(os); } /* PURPOSE: To hold the state of the messaging system, including the * mutexes, conditions and sentence buffers. */ class MessageSystem { // YOUR CODE HERE FOR AN ARRAY OF NUM_CHILDREN+1 MUTEXES // YOUR CODE HERE FOR AN ARRAY OF NUM_CHILDREN+1 CONDITIONS
  • 8. Sentence* sentenceArray[NUM_CHILDREN+1]; // Disallow copy-construction MessageSystem (const MessageSystem&); // Disallow copy-assignment MessageSystem& operator=(const MessageSystem&); public : // PURPOSE: To initialize the array of mutexes, the array of conditions // and the array of sentence pointers to be NULL. MessageSystem () { for (int index = 0; index <= NUM_CHILDREN; index++) { // YOUR CODE HERE TO INITIALIZE MUTEX NUMBER index // YOUR CODE HERE TO INITIALIZE CONDITION NUMBER index sentenceArray[index] = NULL; } } // PURPOSE: To destroy the mutexes in their array, to destroy the conditions // in their array, to delete() the sentence pointers in their array. No // parameters. No return value. ~MessageSystem () { for (int index = 0; index <= NUM_CHILDREN; index++) { // YOUR CODE HERE TO DESTROY MUTEX NUMBER
  • 9. index // YOUR CODE HERE TO DESTROY CONDITION NUMBER index delete(sentenceArray[index]); } } // PURPOSE: To return a *pointer* to the lock at position 'index'. pthread_mutex_t* getLockPtr (int index) { return(/* YOUR CODE HERE TO RETURN A POINTER TO index-th MUTEX */ NULL); } // PURPOSE: To return a *pointer* to the condition at position 'index'. pthread_cond_t* getCondPtr (int index) { return(/* YOUR CODE HERE TO RETURN A POINTER TO index-th CONDITION */ NULL); } // PURPOSE: To "give away" (set equal to NULL) the pointer to the sentence // at position 'index'. Sentence* giveSentencePtr (int index) { Sentence* ptr = sentenceArray[index]; sentenceArray[index] = NULL; return(ptr); }
  • 10. // PURPOSE: To set the sentence pointer at position 'index' equal to // 'sentencePtr'. No return value. void setSentencePtr (int index, Sentence* sentencePtr) { sentenceArray[index] = sentencePtr; } // PURPOSE: To return 'true' if the sentence at position 'index' is ready // to be transmitted. bool isReady (int index) const { return(sentenceArray[index] != NULL); } }; /*------------------------------------------------------------------------ --* *---- ----* *---- Definitions of global variables: --- -* *---- ----* *------------------------------------------------------------------------- -*/ /* PURPOSE: To hold the global messaging system. */
  • 11. MessageSystem messageSystem; /*------------------------------------------------------------------------ --* *---- ----* *---- Definitions of global functions: --- -* *---- ----* *------------------------------------------------------------------------- -*/ /* PURPOSE: To get the necessary locks, get the sentence, print it, * transmit it (imperfectly), and unlock and signal the next child. */ void* child(void* argPtr) { // I. Applicability validity check: // II. Run for current child: // II.A. Get 'index': // YOUR CODE HERE // II.B. Announce that this child is ready: // YOUR CODE HERE
  • 12. // II.C. Get both locks and wait until signaled (if need to): if ( (rand() % 2) == 1) { // YOUR CODE HERE } else { // YOUR CODE HERE } // YOUR CODE HERE // II.D. Get pointer to sentence, print it and transmit it: // YOUR CODE HERE // II.E. Signal next child that message is ready and unlock their // YOUR CODE HERE // III. Finished: } /* PURPOSE: To play the telephone game. 'argc' tells how many command line * arguments there are. 'argv[]' points to each. Returns 'EXIT_SUCCESS' * to OS.
  • 13. */ int main (int argc, const char* argv[]) { // I. Applicability validity check: // II. Play game: // II.A. Seed random number generator: int randNumSeed; if (argc >= 2) randNumSeed = strtol(argv[1],NULL,10); else { string entry; cout << "Random number seed? "; getline(cin,entry); randNumSeed = strtol(entry.c_str(),NULL,10); } srand(randNumSeed); // II.B. Play game: Sentencesentence; int childIndex; int indices[NUM_CHILDREN+1]; // YOUR CODE HERE FOR AN ARRAY OF NUM_CHILDREN+1 THREADS messageSystem.setSentencePtr(0,&sentence);
  • 14. for (childIndex = NUM_CHILDREN; childIndex > 0; childIndex--) { indices[childIndex] = childIndex; // YOUR CODE HERE TO INITIALIZE THREAD NUMBER childIndex } for (childIndex = 1; childIndex <= NUM_CHILDREN; childIndex++) { // YOUR CODE HERE TO WAIT FOR THREAD NUMBER childIndex } cout << "Finally we have: "" << *messageSystem.giveSentencePtr(10) << """ << endl; // III. Finished: return(EXIT_SUCCESS); } Finish class MessageSystem The class needs two more arrays: one of NUM_CHILDREN+1 pthread-mutexes and another of NUM_CHILDREN+1 pthread-conditions. All the objects in both arrays should be initialized in the constructor, destroyed in the destructor, and should have pointers returned in getLockPtr() and getCondPtr(). Write void* child (void* argPtr) It might be useful to define an integer variable index
  • 15. corresponding to the integer pointed to by argPtr. Please note that argPtr has type void* and therefore does not know it points to an integer. A simple cout statement should suffice here. Time for mutexes! See that if statement? In the "then" part of it lock messageSystem.getLockPtr(index) first and messageSystem.getLockPtr(index-1) second. In the "else" part of it lock messageSystem.getLockPtr(index-1) first and messageSystem.getLockPtr(index) second. (We do this to try to convince ourselves that our program is robust over the vagaries of timing.) Then we cout. Finally we loop while our incoming message is not yet ready (method isReady(index-1)). In this loop we should wait to be signaled. Here we've got to get a Sentence* (method giveSentencePtr(index-1)). We print out what we got and call method imperfectlyTransmit() on it (how do you run a method on an object given a pointer to it?). Finally we set the updated sentence with setSentencePtr(index,yourSentencePtrVar) We got both locks index-1 and index, and here we unlock them. Further, we should signal that there's a Sentence pointer in the buffer at index for child index+1. Finish int main () We need an array of NUM_CHILDREN+1 pthreads.
  • 16. This array will be initialized in the first loop, where all child threads are to run your function child() and all are passed the address of indices[childIndex]. The child threads are initialized in reverse order to show how robust our solution is; our children are well-behaved and will not throw a tantrum if made to wait. In the second loop we wait for each thread to finish. Sample output:[[email protected] Assign3]$ telephoneGame 1 Child 9 ready to start Child 9 got all his/her locks Child 9 surrendering lock waiting for signal Child 8 ready to start Child 8 got all his/her locks Child 8 surrendering lock waiting for signal Child 7 ready to start Child 7 got all his/her locks Child 7 surrendering lock waiting for signal Child Child 106 ready to start ready to start Child 6 got all his/her locks Child 6 surrendering lock waiting for signal Child 5 ready to start Child 5 got all his/her locks Child 5 surrendering lock waiting for signal Child 4 ready to start Child 4 got all his/her locks Child 4 surrendering lock waiting for signal Child 3 ready to start Child 3 got all his/her locks Child 3 surrendering lock waiting for signal Child 2 ready to start Child 2 got all his/her locks Child 2 surrendering lock waiting for signal Child 1 ready to start
  • 17. Child 1 got all his/her locks Child 1 says "The quick brown fox jumped over the lazy dog." Child 2 says "The quick brown fox jumped clover the lazy dog." Child 3 says "The quick brown fox jumped clover the lazy dog." Child 4 says "The quick brown fox jumped clover the lazy dog." Child 5 says "The quick brown fox jumped clover the lazy dog." Child 6 says "The quick brown fox jumped clover the hazy dog." Child 7 says "The quick brown fox jumped clover the hazy hog." Child 8 says "The quick brown fox jumped clover the hazy hog." Child 9 says "The quick brown fox jumped clover the hazy hog." Child 10 got all his/her locks Child 10 says "The quick brown fox jumped clover the hazy frog." Finally we have: "The slick brown fox jumped clover the hazy frog." [[email protected] Assign3]$ telephoneGame 2 Child Child 10 ready to start9 ready to start Child 10 got all his/her locks Child 10 surrendering lock waiting for signal Child 9 got all his/her locks Child 9 surrendering lock waiting for signal Child 8 ready to start Child 8 got all his/her locks Child 8 surrendering lock waiting for signal Child 6 ready to start Child 6 got all his/her locks Child 6 surrendering lock waiting for signal Child 7 ready to start Child 5 ready to start Child 5 got all his/her locks Child 5 surrendering lock waiting for signal
  • 18. Child 4 ready to start Child 4 got all his/her locks Child 4 surrendering lock waiting for signal Child 3 ready to start Child 3 got all his/her locks Child 3 surrendering lock waiting for signal Child 2 ready to start Child 2 got all his/her locks Child 2 surrendering lock waiting for signal Child 1 ready to start Child 1 got all his/her locks Child 1 says "The quick brown fox jumped over the lazy dog." Child 2 says "The quick brown fox jumped over the lazy dog." Child 3 says "Wee quick brown fox jumped over the lazy dog." Child 4 says "Wee quick brown fox jumped over the lazy dog." Child 5 says "Wee quick brown fox jumped over the lazy dog." Child 6 says "Wee quick brown locks jumped over the lazy dog." Child 7 got all his/her locks Child 7 says "Wee quick brown locks jumped over the lazy hog." Child 8 says "Wee quick brown locks jumped over the lazy hog." Child 9 says "Wee slick brown locks jumped over the lazy hog." Child 10 says "Wee slick brown locks jumped over the lazy hog." Finally we have: "The slick brown locks jumped over the lazy hog." [[email protected] Assign3]$ telephoneGame 3 Child 10 ready to start Child 10 got all his/her locks Child 10 surrendering lock waiting for signal Child 9 ready to start Child 9 got all his/her locks Child 9 surrendering lock waiting for signal Child 8 ready to start
  • 19. Child 8 got all his/her locks Child 8 surrendering lock waiting for signal Child 7 ready to start Child 7 got all his/her locks Child 7 surrendering lock waiting for signal Child 6 ready to start Child 6 got all his/her locks Child 6 surrendering lock waiting for signal Child 5 ready to start Child 5 got all his/her locks Child 5 surrendering lock waiting for signal Child 4 ready to start Child 4 got all his/her locks Child 4 surrendering lock waiting for signal Child 3 ready to start Child 3 got all his/her locks Child 3 surrendering lock waiting for signal Child 2 ready to start Child 2 got all his/her locks Child 2 surrendering lock waiting for signal Child 1 ready to start Child 1 got all his/her locks Child 1 says "The quick brown fox jumped over the lazy dog." Child 2 says "The quick brown fox thumped over the lazy dog." Child 3 says "He quick brown fox thumped over the lazy dog." Child 4 says "He quick brown fox jumped over the lazy dog." Child 5 says "He quick brown fox jumped over be lazy dog." Child 6 says "He quick brown fox jumped over be lazy dog." Child 7 says "He quick brown fox jumped over be lazy dog." Child 8 says "He quick brown fox jumped over be lazy dog." Child 9 says "He quick brown fox pumped over be lazy dog." Child 10 says "He quick found fox pumped over be lazy dog." Finally we have: "He slick found fox pumped over be lazy dog." [[email protected] Assign3]$ telephoneGame 4 Child Child Child 109 ready to start ready to start Child 9 got all his/her locks
  • 20. Child 9 surrendering lock waiting for signal 8 ready to start Child 8 got all his/her locks Child 8 surrendering lock waiting for signal Child 7 ready to start Child 7 got all his/her locks Child 7 surrendering lock waiting for signal Child 6 ready to start Child 6 got all his/her locks Child 6 surrendering lock waiting for signal Child 5 ready to start Child 5 got all his/her locks Child 5 surrendering lock waiting for signal Child 4 ready to start Child 4 got all his/her locks Child 4 surrendering lock waiting for signal Child 1 ready to start Child 1 got all his/her locks Child 1 says "The quick brown fox jumped over the lazy dog." Child 3 ready to start Child 3 got all his/her locksChild Child 3 surrendering lock waiting for signal 2 ready to start Child 2 got all his/her locks Child 2 says "The quick brown fox jumped white cliffs of Dover the lazy dog." Child 3 says "The quick brown fox pumped white cliffs of Dover the lazy dog." Child 4 says "The quick brown fox jumped white cliffs of Dover the lazy dog." Child 5 says "The slick brown fox jumped white cliffs of Dover the lazy dog." Child 6 says "The slick brown fox jumped white cliffs of Dover three lazy dog." Child 7 says "The slick brown fox jumped white cliffs of Dover
  • 21. three lazy dog." Child 8 says "The slick brown fox jumped white cliffs of Dover the lazy dog." Child 9 says "He slick brown fox jumped white cliffs of Dover the lazy dog." Child 10 got all his/her locks Child 10 says "He slick brown fox jumped white cliffs of Dover the lazy dog." Finally we have: "He slick brown box jumped white cliffs of Dover the lazy dog." [[email protected] Assign3]$ telephoneGame 5 Child Child 9 ready to start10 ready to start Child 9 got all his/her locks Child 9 surrendering lock waiting for signal Child 8 ready to start Child 8 got all his/her locks Child 8 surrendering lock waiting for signal Child 6 ready to start Child 6 got all his/her locks Child 6 surrendering lock waiting for signal Child 7 ready to start Child 5 ready to start Child 5 got all his/her locks Child 5 surrendering lock waiting for signal Child 4 ready to start Child 4 got all his/her locks Child 4 surrendering lock waiting for signal Child 3 ready to start Child 3 got all his/her locks Child 3 surrendering lock waiting for signal Child 2 ready to start Child 2 got all his/her locks Child 2 surrendering lock waiting for signal Child 1 ready to start Child 1 got all his/her locks
  • 22. Child 1 says "The quick brown fox jumped over the lazy dog." Child 2 says "Wee quick brown fox jumped over the lazy dog." Child 3 says "The quick brown fox jumped over the lazy dog." Child 4 says "The thick brown fox jumped over the lazy dog." Child 5 says "The thick brown fox jumped over the lazy dog." Child 6 says "The thick brown fox pumped over the lazy dog." Child 7 got all his/her locks Child 7 says "The thick brown fox pumped over the lazy frog." Child 8 says "The thick brown fox pumped over the lazy frog." Child 9 says "The thick brown locks pumped over the lazy frog." Child 10 got all his/her locks Child 10 says "The thick brown locks thumped over the lazy frog." Finally we have: "The thick brown locks thumped clover the lazy frog." [[email protected] Assign3]$ telephoneGame 6 Child 9 ready to start Child 9 got all his/her locks Child 9 surrendering lock waiting for signal Child 8 ready to start Child 8 got all his/her locks Child 8 surrendering lock waiting for signal Child 7 ready to start Child 7 got all his/her locks Child 7 surrendering lock waiting for signal Child 6 ready to start Child 6 got all his/her locks Child 6 surrendering lock waiting for signal Child 5 ready to start Child 5 got all his/her locks Child 5 surrendering lock waiting for signal Child 4 ready to start Child 4 got all his/her locks Child 4 surrendering lock waiting for signal Child 3 ready to start
  • 23. Child 3 got all his/her locks Child 3 surrendering lock waiting for signal Child 2 ready to start Child 2 got all his/her locks Child 2 surrendering lock waiting for signal Child 1 ready to start Child 1 got all his/her locks Child 1 says "The quick brown fox jumped over the lazy dog." Child 2 says "The quick brown fox pumped over the lazy dog." Child 3 says "The quick brown fox pumped over the lazy dog." Child 4 says "The quick brown fox pumped over the lazy frog." Child 5 says "The quick brown fox pumped over the lazy frog." Child 6 says "The quick brown fox pumped over the lazy frog." Child 7 says "The quick brown fox pumped over the lazy frog." Child 8 says "The quick brown fox pumped clover the lazy frog." Child 9 says "The quick brown locks pumped clover the lazy frog." Child 10 ready to start Child 10 got all his/her locks Child 10 says "The quick brown locks pumped clover the lazy dog." Finally we have: "The quick brown locks pumped over the lazy dog." [[email protected] Assign3]$ Useful knowledge: Function What it does int pthread_create (/* Pointer to a pthread_t object */ pthread_t* restrict threadPtr, /* Pointer to optional object for properties of child */ const pthread_attr_t* restrict attr,
  • 24. /* Name of function to run: void* fncName(void* ptr) */ void *(*fncName)(void*), /* Ptr to object that is parameter to fncName() */ void *restrict arg ) Makes a thread in the space pointed to by threadPtr The thread run the function void* fncName(void* ) and passes arg to it. Just leave attr as NULL for a generic thread. int pthread_join (/* Which thread to wait for */ pthread_t thread, /* Pointer to pointer to receive pointer returned by exiting thread's function. */ void** valuePtrsPtr ) Waits for thread thread to finish. When it does valuePtr (the thing that valuePtrsPtr points to) is set to the thread's function's returned pointer value or it is ignored if valuePtr==NULL int pthread_mutex_init (/* Ptr to space for mutex */ pthread_mutex_t *restrict mutexPtr, /* Type of mutex (just pass NULL) */ const pthread_mutexattr_t *restrict attr ); Initializes lock object pointed to by mutexPtr. Just use NULL for 2nd parameter. int pthread_mutex_destroy
  • 25. (/* Ptr to mutex to destroy *. pthread_mutex_t *mutex ); Releases resources taken by mutex pointed to by mutexPtr. int pthread_mutex_lock (/* Pointer to mutex to lock */ pthread_mutex_t *mutexPtr ); Either Gains lock and proceeds, or Waits for lock to become available int pthread_mutex_unlock (/* Pointer to mutex to unlock */ pthread_mutex_t *mutexPtr ); Releases lock. int pthread_cond_init (/* Pointer to space in which to make condition */ pthread_cond_t *restrict condPtr, /* Type of condition (just pass NULL) */ const pthread_condattr_t *restrict attr ); Creates a condition. int pthread_cond_destroy (/* Pointer to condition to destroy */ pthread_cond_t *condPtr ); Destroys pointed to condition. int pthread_cond_wait (/* Pointer to condition on which to wait */
  • 26. pthread_cond_t *restrict condPtr, /* Pointer to mutex to surrender until receive signal */ pthread_mutex_t *restrict mutexPtr ); Suspends thread until receives signal on condPtr. While thread is suspended it surrenders lock on mutexPtr int pthread_cond_signal (/* Ptr to condition which is signaled */ pthread_cond_t *condPtr ); Wakes up at least one thread waiting for signal on condPtr. Good C String Programming (30 Points) Below there's a C program that is a case study in bad string programming in C. Re-write it into a proper C program that uses the C string library. Please note: For the C program the character arrays are too small, so the program will not let you enter everything and it's output will be bad. That's okay! We're trying to prevent crashing programs and buffer-overflow attacks! /*------------------------------------------------------------------------ -* *--- ---* *--- memoryNoNos.c ---*
  • 27. *--- ---* *--- This program makes all kinds of mistakes with C strings. ---* *--- Fix them! If you choose to make fixed-length arrays make them ---* *--- no bigger than 'MAX_STRING'. 'MAX_STRING' is too small for ---* *--- most applications, and that is the point. We want to prove ---* *--- that even if the strings are too small we are not subject to ---* *--- buffer overflow attacks. ---* *--- ---* *--- ---- ---- ---- ---- ---- ---- ---- ---- ---* *--- ---* *--- Version 1.0 Joseph Phillips 2015 August 6 --- * *--- ---* *------------------------------------------------------------------------- */ #include <stdlib.h> #include <stdio.h> #include <string.h> #define MAX_STRING 30 // PURPOSE: To replace the newline character (if present) in the string // pointed to by 'cPtr' with the null-character ('0'). No return value. // // NOTE: Assumes that the string pointed to by 'cPtr' is '0' terminated! void removeNewline (char* cPtr
  • 28. ) { cPtr = strchr(cPtr,'n'); if (cPtr != NULL) *cPtr = '0'; } char* getName () { char* name; printf("Please enter your name: "); gets(name); removeNewline(name); return(name); } void getIcecreamFlavor (char* icecreamFlavor) { printf("Please enter the last flavor of ice cream that you ate: "); gets(icecreamFlavor); removeNewline(icecreamFlavor); } char* getCakeFlavor () { char* cakeFlavor; printf("Please enter the last flavor of cake that you ate: "); gets(cakeFlavor); removeNewline(cakeFlavor);
  • 29. return(cakeFlavor); } char* report (const char* name, const char* icecreamFlavor, const char* cakeFlavor ) { char toReturn[MAX_STRING]; if (icecreamFlavor == cakeFlavor) sprintf(toReturn,"%s, you sure love %s!n",name,icecreamFlavor); else sprintf(toReturn,"%s, change is good!n",name); return(toReturn); } int main () { char* name; char* icecreamFlavor; char* cakeFlavor; name = getName(); getIcecreamFlavor(icecreamFlavor); cakeFlavor = getCakeFlavor(); printf(report(name,icecreamFlavor,cakeFlavor)); return(EXIT_SUCCESS); }