Question: Safe Stack The C program stack - ptr . c ( provided ) contains an implementation of a stack using a linked list. An example
Safe Stack
The C program stackptrc provided contains an implementation of a stack using a linked list.
An example of its use is as follows:
StackNode top NULL;
push ⊤
push ⊤
push ⊤
int value pop⊤
value pop⊤
value pop⊤
This program currently has a race condition and is not appropriate for a concurrent environment. Using
Pthreads mutex locks section fix the race conditions. Test your nowthreadsafe stack by
creating concurrent threads in main that intermix pushing and popping values.
Use a loop in main to create all those threads. Apply all the things you've learned about creating
and joining threads from previous chapters.
Write one testStack function, and use it as the entry point for each thread.
The testStack function should intermix push operations with pop operations in a loop that
executes times.
All threads use the same stack.
gcc pthread stackptrc o stackptr is an example command to compile and link
your program
If you're up for it you may rewrite the provided C program into wellformed C code using proper
Object Oriented Design concepts, but you must maintain the dynamically allocated linked list
concept, and you must still use the Pthreads mutex locks.
Stack containing race conditions
#include
#include
#include
Linked list node
typedef int valuet;
typedef struct Node
valuet data;
struct Node next;
StackNode;
Stack function declarations
void push valuet v StackNode top;
valuet pop StackNode top;
int isempty StackNode top;
int mainvoid
StackNode top NULL;
push ⊤
push⊤
pop ⊤
push⊤
pop ⊤
pop ⊤
push⊤
push ⊤
pop ⊤
push⊤
pop ⊤
pop ⊤
push⊤
pop ⊤
push⊤
return ;
Stack function definitions
void pushvaluet v StackNode top
StackNode newnode mallocsizeofStackNode;
newnodedata v;
newnodenext top;
top newnode;
valuet popStackNode top
if isemptytop return valuet;
valuet data topdata;
StackNode temp top;
top topnext;
freetemp;
return data;
int isemptyStackNode top
if top NULL return ;
else return ;
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
