c++ - 将线程与堆栈一起使用 (C++)

标签 c++

我尝试使用线程创建堆栈,我的代码:

推送函数(m为互斥锁)

void Stack::Push(int num){  
    m.lock();
    sta[current++] = num;
    m.unlock();
}

弹出函数:

int Stack::Pop(){
    if (current > 0){
        m.lock();
        int a = sta[--current];
        m.unlock();
        return a;
    }
    return sta[0];
}

主要内容:

void threadsPrint(string s){
    m1.lock();
    cout << s << endl;
    m1.unlock();
}

void func(Stack & t){
    threadsPrint("T1 Push 1\n");
    t.Push(1);
    threadsPrint("T1 Push 2\n");
    t.Push(2);
    threadsPrint("T1 Push 3\n");
    t.Push(3);
    threadsPrint("T1 Push 4\n");
    t.Push(4);
    threadsPrint("T1 Push 5\n");
    t.Push(5);
    threadsPrint("T1 Push 6\n");
    t.Push(6);
}

void func2(Stack & t){
    threadsPrint("T2 Pop "+to_string(t.Pop())+"\n");
    threadsPrint("T2 Pop " + to_string(t.Pop()) + "\n");
    threadsPrint("T2 Pop " + to_string(t.Pop()) + "\n");
    threadsPrint("T2 Pop " + to_string(t.Pop()) + "\n");
    threadsPrint("T2 Pop " + to_string(t.Pop()) + "\n");
    threadsPrint("T2 Pop " + to_string(t.Pop()) + "\n");
}

int main(){
    Stack t;

    thread t1(func,ref(t));
    thread t2(func2,ref(t));
    t1.join();
    t2.join();
    return 0;
}

输出:

   T1 Push 1

   T2 Pop -842150451

   T1 Push 2

   T2 Pop 1

   T1 Push 3

   T2 Pop 2

   T1 Push 4

   T2 Pop 3

   T1 Push 5

   T2 Pop 4

   T1 Push 6

   T2 Pop 5

我知道这是糟糕的代码,但我只是想使用线程 我仍然没有得到正确的结果,我必须如何修复代码?

最佳答案

if current > 0){
    m.lock();

您不能在 m.lock() 之外检查 current。受比赛条件限制。

int Stack::Pop(){
  m.lock();
  int a = current ? sta[--current] : sta[0];
  m.unlock();
  return a;
}

但是您的堆栈仍然无法从根本上区分是弹出最后一项还是弹出空堆栈。我个人更喜欢这样的东西:

boolean Stack::Pop(int& val){
  boolean ret = false;
  m.lock();
  if (current) {
     val = sta[--current];
     ret = true;
  }
  m.unlock();
  return ret;
}

等待堆栈增长的问题,当它为空时,委托(delegate)给调用者。具有等待和信号的完全成熟的生产者-消费者堆栈超出了此处的范围。

当然,lock()/unlock()应该是RAII .

关于c++ - 将线程与堆栈一起使用 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26341786/

相关文章:

c++ - 我如何判断用户是否试图在 C++ 中关闭窗口?

c++ - C 方法是否可能无法包含在 C++ 项目中?

c++ - 正则表达式中的 If-Then-Else 条件语句和使用捕获组

c++ - int *tab1[5];但动态地

c++ - 是否有一个 gtest 等同于夹具级设置/拆卸?

c++ - 读取用于在图书馆计算机系统中搜索的一组关键字文档的文件

c++ - 构造函数初始化列表中的非成员初始化

c++ - 对 pop_back() 感到困惑,C++

c++ - operator== 使用 msvc 编译,但不使用 gcc 和 clang 编译

c++ - 为什么 printf() 将 float 提升为 double ?