RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 924023
Accepted
Mikhailo
Mikhailo
Asked:2020-12-22 14:37:04 +0000 UTC2020-12-22 14:37:04 +0000 UTC 2020-12-22 14:37:04 +0000 UTC

条件变量 - 错误在哪里?

  • 772

由于其他人的问题,我再次提出了一个问题——这次是这个问题。

我想尝试并行编程并通过条件变量解决问题(一个线程将字符串添加到列表中,另一个从那里获取它们,对它们进行排序并将它们写入自己的线程)。它似乎有效,但有时会关闭

......
<-- String consumed
<-- Wait string produced
--> String produced
--> Wait string consumed

值得。我哪里傻了?如果我尝试向条件变量添加条件,它只会变得更糟。

这是我的代码:

#include <list>
#include <string>
#include <iostream>
#include <iomanip>
#include <thread>
#include <condition_variable>
#include <algorithm>
#include <ctime>

using namespace std;

constexpr int ELEMENTS = 10;

void printList(const list<string>& l) {
    cout <<"LIST:\n";
    for(const auto& s: l) cout << s << " ";
    cout << endl;
    }

string new_string() {
    string s;
    for(int i = rand()%8+1; i > 0; --i)
        s += rand()%26+'a';
    return s;
    }

// Сигналы о том, что строка готова и что обработана
condition_variable strReady, strHandled;
mutex mReady, mHandled;

void createList(list<string>& l) {
        {
        unique_lock lck(mHandled); // Ждем запуска второго потока
        strHandled.wait(lck);      // Без проверок, так как заведомо знаем,
        }                              // что он один

    for(int i = 0; i < ELEMENTS; ++i) {
        // Начинает создавать
        string s = new_string();
        l.push_back(s);

        cout << "--> String produced" << endl;

        strReady.notify_one();     // Уведомляем о готовности строки

        cout << "--> Wait string consumed" << endl;

        unique_lock lck(mHandled); // и ждем разрешения работать
        strHandled.wait(lck);      // Без проверок, так как заведомо знаем,
        }                              // что поток обработчика единственный
    }

void handleList(list<string>& l1, list<string>& l2) {

    strHandled.notify_one();       // Сообщаем о запуске, можно работать

    for(int i = 0; i < ELEMENTS; ++i) {
        string s;
        // Ждет сигнала
            {
            unique_lock lck(mReady);
            strReady.wait(lck);    // Без проверок, так как заведомо знаем,
            // что поток создателя единственный

            s = l1.back();
            cout << "<-- String consumed" << endl;
            }

        strHandled.notify_one();   // Строка скопирована, сообщаем, что
        // можно работать дальше
        sort(s.begin(),s.end());
        l2.push_back(s);
        cout << "<-- Wait string produced" << endl;
        }
    }

int main() {
    srand(time(0));

    list<string> l1, l2;
    thread t1(createList,ref(l1));
    thread t2(handleList,ref(l1),ref(l2));
    t1.join();
    t2.join();

    printList(l1);
    printList(l2);

    }

仍然 neponyatka - is srand(time(0)),但线条总是相同的。

c++
  • 2 2 个回答
  • 10 Views

2 个回答

  • Voted
  1. Best Answer
    ixSci
    2020-12-24T14:56:12Z2020-12-24T14:56:12Z

    您的代码有几个问题,难度不同。首先,一些无用的开场白:

    {
        unique_lock lck(mHandled); // Ждем запуска второго потока
        strHandled.wait(lck);      // Без проверок, так как заведомо знаем,
    }  
    

    和strHandled.notify_one();- 删除。不需要这些序言。第二:

    没有检查,因为我们确定处理程序线程是唯一的

    需要检查,因为 有一个虚假的唤醒。那些。线程可以唤醒不是因为它收到了信号,而仅仅是因为。所以总是需要额外的检查。

    第三,你的代码中有一个竞赛,这意味着 UB。在第一个线程中,您l.push_back(s);没有保护互斥锁,这会与第二个线程的这条线产生竞争:s = l1.back();. 关闭使用互斥锁将字符串添加到列表mReady并离开。

    一般来说,因为 您正在尝试完全序列化 2 个线程,即 为了使它们顺序可执行,一个互斥体对你来说就足够了——你不需要两个,只有一个资源。

    第四,也是最重要的,如果它strReady.notify_one();被执行并立即切换到另一个线程,即 wait没有时间处理,那么第二个线程的所有代码都有时间处理,包括strHandled.notify_one();,这将导致信号会飞入宇宙而第一个线程永远不会知道它是。正确排列互斥锁以消除这种情况,然后挂起应该停止。

    但是为了使代码正确,您需要应用所有注释。


    通过最低限度地更改原始代码,您可以获得如下内容:

    condition_variable strReady, strHandled;
    mutex mGuard;
    
    void createList(list<string>& l) {
        for(int i = 0; i < ELEMENTS; ++i) {
            string s = new_string();
            unique_lock lck(mGuard);
            l.push_back(s);
            cout << "--> String produced" << endl;
            strReady.notify_one(); 
            cout << "--> Wait string consumed" << endl;
            strHandled.wait(lck);      
        } 
    }
    
    void handleList(list<string>& l1, list<string>& l2) {
    
        size_t processed{0};
        for(int i = 0; i < ELEMENTS; ++i) {
            string s;
            {
                unique_lock lck(mGuard);
                strReady.wait(lck, [&](){ return processed < l1.size(); });
                s = l1.back();
                ++processed;
                cout << "<-- String consumed" << endl;
            }
            strHandled.notify_one();  
            sort(s.begin(), s.end());
            l2.push_back(s);
            cout << "<-- Wait string produced" << endl;
        }
    }
    

    明显的缺点:没有消费者实际消费的生产者流通知。因此,您必须为输出和通知保留互斥锁,并且由于虚假唤醒而导致“过度生产”也没有任何保护措施,但这个想法应该很清楚。

    • 2
  2. Harry
    2020-12-22T19:48:33Z2020-12-22T19:48:33Z

    我怀疑仍然有必要向条件变量添加条件,以避免即使使用单个线程也会出现误报。让我们在列表中添加一个变量就绪标志:

    #include <list>
    #include <string>
    #include <iostream>
    #include <iomanip>
    #include <thread>
    #include <condition_variable>
    #include <algorithm>
    #include <ctime>
    
    using namespace std;
    
    constexpr int ELEMENTS = 20;
    
    void printList(const list<string>& l) {
        cout <<"LIST:\n";
        for(const auto& s: l) cout << s << " ";
        cout << endl;
    }
    
    string new_string() {
        string s;
        for(int i = rand()%8+1; i > 0; --i)
            s += rand()%26+'a';
        return s;
    }
    
    condition_variable strReady, strHandled;
    mutex mReady, mHandled;
    bool isReady = false;
    
    void createList(list<string>& l) {
    
        srand(time(0));
    
        for(int i = 0; i < ELEMENTS; ++i) {
            string s = new_string();
            l.push_back(s);
    
            cout << "--> String produced\n";
    
            isReady = true;
            strReady.notify_all(); 
    
            cout << "--> Wait string consumed\n";
    
            unique_lock lck(mHandled); 
            strHandled.wait(lck,[]() {return !isReady;}); 
        }
    }
    
    void handleList(list<string>& l1, list<string>& l2) {
    
        for(int i = 0; i < ELEMENTS; ++i) {
            string s;
            {
                unique_lock lck(mReady);
                strReady.wait(lck,[]() {return isReady;});
    
                s = l1.back();
                cout << "<-- String consumed\n";
            }
    
            isReady = false;
            strHandled.notify_all(); 
    
            sort(s.begin(),s.end());
            l2.push_back(s);
            cout << "<-- Wait string produced\n";
        }
    }
    
    int main() {
    
        list<string> l1, l2;
        thread t1(createList,ref(l1));
        thread t2(handleList,ref(l1),ref(l2));
        t1.join();
        t2.join();
    
        printList(l1);
        printList(l2);
    
    }
    
    • 0

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    是否可以在 C++ 中继承类 <---> 结构?

    • 2 个回答
  • Marko Smith

    这种神经网络架构适合文本分类吗?

    • 1 个回答
  • Marko Smith

    为什么分配的工作方式不同?

    • 3 个回答
  • Marko Smith

    控制台中的光标坐标

    • 1 个回答
  • Marko Smith

    如何在 C++ 中删除类的实例?

    • 4 个回答
  • Marko Smith

    点是否属于线段的问题

    • 2 个回答
  • Marko Smith

    json结构错误

    • 1 个回答
  • Marko Smith

    ServiceWorker 中的“获取”事件

    • 1 个回答
  • Marko Smith

    c ++控制台应用程序exe文件[重复]

    • 1 个回答
  • Marko Smith

    按多列从sql表中选择

    • 1 个回答
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Suvitruf - Andrei Apanasik 什么是空? 2020-08-21 01:48:09 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5