In: Computer Science
The program ( stack-ptr.c ) implements stack using a linked list, however, it contains a race condition and is not appropriate for a concurrent environment. Using Pthreads mutex locks, fix the race condition. For reference, see Section 7.3.1 of SGG book.(Section 7.3.1 is about mutex and semaphores it does explain how to implement I'm just having a hard time finding the race condition within the code)
/*
* Stack containing race conditions
*/
#include
#include
#include
typedef int value_t;
// Node structure
typedef struct Node
{
value_t data;
struct Node *next;
} StackNode;
// function prototypes
void push(value_t v, StackNode **top, pthread_mutex_t
*mutex);
value_t pop(StackNode **top, pthread_mutex_t *mutex);
int is_empty(StackNode *top);
void push(value_t v, StackNode **top, pthread_mutex_t *mutex)
{
StackNode *new_node;
new_node = (StackNode *)malloc(sizeof(StackNode));
new_node->data = v;
// mutex lock and unlock code
}
value_t pop(StackNode **top, pthread_mutex_t *mutex)
{
StackNode *temp;
pthread_mutex_lock(mutex);
// mutex lock and unlock code based on empty or full stack
}
int is_empty(StackNode *top) {
if (top == NULL)
return 1;
else
return 0;
}
int main(void)
{
StackNode *top = NULL;
// pthread_mutex variable declarion and verify push/pop operation
for 4 inputs (5, 10, 15, 20)
return 0;
}
#include <exception>
#include <memory>
#include <mutex>
#include <stack>
struct empty_stack: std::exception
{
const char* what() const throw();
};
template<typename T>
class threadsafe_stack
{
private:
std::stack<T> data;
mutable std::mutex m;
public:
threadsafe_stack(){}
threadsafe_stack(const threadsafe_stack& other)
{
std::lock_guard<std::mutex> lock(other.m);
data=other.data;
}
threadsafe_stack& operator=(const threadsafe_stack&) = delete;
void push(T new_value)
{
std::lock_guard<std::mutex> lock(m);
data.push(new_value);
}
std::shared_ptr<T> pop()
{
std::lock_guard<std::mutex> lock(m);
if(data.empty()) throw empty_stack();
std::shared_ptr<T> const res(std::make_shared<T>(data.top()));
data.pop();
return res;
}
void pop(T& value)
{
std::lock_guard<std::mutex> lock(m);
if(data.empty()) throw empty_stack();
value=data.top();
data.pop();
}
bool empty() const
{
std::lock_guard<std::mutex> lock(m);
return data.empty();
}
};