在最近的一次采访中,我被要求在Linux机器上用C++实现一个线程安全的通用(基于ietemplate)堆栈.
我很快想出了以下内容(它可能有编译错误).
我完成了.面试官可能喜欢这个实现中的一些东西.也许是设计部分:)
以下是此实现可能具有的一些问题: -
1.表示溢出/下溢的实现不正确.因为我使用STL向量作为底层数据结构,所以没有溢出处理.应该有这样的处理吗?此外,下溢(在Pop()中)产生false作为返回值.应该通过抛出异常来完成吗?
2. PopElem例程的实现.以下实施是否正确?
3.没有真正使用顶级元素.
4.编写器和读者线程启动之间的更好时间.
请提出任何意见/建议/改进.
谢谢.
//实现线程安全的通用堆栈.
#include<pthread.h>
#include<iostream>
#include<vector>
using namespace std;
template<typename T>
class MyStack
{
public:
//interface
bool Push(T elem);
bool Pop(T& elem);
bool IsEmpty();
//constructor
MyStack() {
pthread_mutex_init(&lock);
top = 0;
}
//destructor
~MyStack() {
pthread_mutex_destroy(&lock);
}
private:
pthread_mutex_t lock;
int top;
vector<T> stack;
bool MyStack::Push(T elem);
bool MyStack::PopElem(T& elem);
}; //end of MyStack
template<typename T>
bool MyStack<T>::Push(T elem)
{
pthread_mutex_lock(&lock);
PushElem(elem);
pthread_mutex_unlock(&lock);
}
template<typename T>
bool MyStack<T>::Pop(T& elem)
{ …Run Code Online (Sandbox Code Playgroud)