【问题标题】:Communication between threads not working - C++线程之间的通信不起作用 - C++
【发布时间】:2018-09-18 06:07:33
【问题描述】:

我正在尝试编写一个简单的示例来说明两个线程(生产者和消费者)之间的经典通信。生产者锁定互斥体,产生随机字符串消息并将它们推送到队列并释放锁定。然后消费者锁定互斥锁并在屏幕上打印该数据。出于某种原因,在运行代码后,我得到空白终端一段时间,然后程序终止而没有任何输出!这是我的代码:

#include <iostream>
#include <stdlib.h>
#include <thread>
#include <mutex>
#include <queue>
#include <random>
#include <string>
#include <cstdlib>

using namespace std;

static mutex mmutex;
static condition_variable mcond;
static queue <string> mqueue;

void consumer() {
    while (true) {
        unique_lock<mutex> lck{mmutex};
        mcond.wait(lck);
        string new_string = "producer has not produced yet ";
        string m = "";
        if (!mqueue.empty()) {
            m = mqueue.front();
            mqueue.pop();
            string new_string = "producer produced " + m;
        }   
        cout << new_string << endl;
        lck.unlock();
    }
}

void producer() {
    while (true) {
        string new_msg = NULL;
        unique_lock<mutex> lck{mmutex};
        int random = rand() % 40 + 40;
        new_msg = "New Random Char is "+static_cast <char> (random);
        mqueue.push(new_msg);
        mcond.notify_one();
    }
}




int main() {

    thread t1{ producer };
    thread t2{ consumer };


    t1.join();
    t2.join();
    cout << "exiting"<<endl;
    system("PAUSE");
    exit(0);
}

【问题讨论】:

  • 让你的线程相互通信的概念本身就是一种糟糕的编码习惯。线程必须是原子的和正交的。
  • Doesn't even compile。请发布真实代码以获得帮助。
  • @πάντα ῥεῖ 抱歉,我忘了添加“使用命名空间标准;”现在修复了
  • @MegaMind 这是一个相当大胆的断言。
  • 使用调试器。

标签: c++ multithreading mutex


【解决方案1】:

总的来说,你得到的同步方案很好。除了代码有一个运行时错误、使用std::strings 的一些意外后果以及对unlock() 的std::unique_ptr 的不必要(并且可能误导读者)调用。

运行代码后,我得到空白终端一段时间,然后 程序终止,没有任何输出

由于将指向 null 的指针分配给 std::string,它挂起并终止:

string new_msg = NULL;

你可以see here,这将导致std::string实例尝试访问这个零地址:(

其次,您无法通过 将 字符串文字 与 char 连接起来,如以下几行所示:

string new_string = "producer produced " + m;

和

new_msg = "New Random Char is "+static_cast <char> (random);

这是您的线程过程的一个工作的、稍微更好的书面版本,您可以在其中看到各种有效的方法来初始化和分配给std::string 以获得您想要的。再次注意将lck.unlock(); 删除为std::unique_lock 是一个RAII 对象,它将在mutex 在while 作用域的出口处按原样销毁时释放它:

void consumer() {
    while (true) {
        unique_lock<mutex> lck{ mmutex };
        mcond.wait(lck);
        string new_string;
        if (!mqueue.empty()) {
            string m = mqueue.front();
            mqueue.pop();
            new_string = string("producer produced ") + m;
        }
        else
        {
            new_string = "producer has not produced yet ";
        }
        cout << new_string << endl;
        //lck.unlock(); // <--- Not the intended usage of `unique_lock`
    }
}

void producer() {
    while (true) {
        string new_msg("New Random Char is ");
        unique_lock<mutex> lck{ mmutex };
        int random = rand() % 40 + 40;
        new_msg += static_cast<char>(random);
        mqueue.push(new_msg);
        mcond.notify_one();
    }
}

输出:

producer produced New Random Char is F
producer produced New Random Char is =
producer produced New Random Char is K
producer produced New Random Char is N
producer produced New Random Char is *
producer produced New Random Char is :
producer produced New Random Char is 3
producer produced New Random Char is O
producer produced New Random Char is @
producer produced New Random Char is E
producer produced New Random Char is I
...

【讨论】:

    【解决方案2】:

    这段代码不是很好。如果你在调试器中运行它,你很快就会发现它停止的原因,那就是......

    string new_msg = NULL;
    

    这是一个访问冲突,其中 0 (NULL) 处的字节被读取以获取字符串。

    更正:

    string new_msg;  // default value is empty.
    

    删除后,需要进行一些必要的更改以使代码更接近预期的行为..

    new_msg = "New Random Char is "+static_cast <char> (random);
    

    这不起作用,因为它需要字符串的地址,并添加 40 到 80 个字节。它从字符串中移出到某个“随机位置”。最初的 C 兼容性在这里出现,而正确的(我相信)做事的方法是......

    new_msg = string("New Random Char is ") +static_cast <char> (random);
    

    当转换为 std::string 时,+ 现在表现为附加运算符。

    终于在消费者中...

    string new_string = "producer produced " + m;
    

    需要

    new_string = "producer produced " + m;
    

    否则用于计算结果的变量new_string与读取队列的变量不同。

    最后,在我的测试中,消费者跟不上生产者的步伐,需要某种形式的节流和结束条件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-28
      • 1970-01-01
      相关资源
      最近更新 更多