c++ - 两个线程之间的同步队列

标签 c++ multithreading c++11

这是一个简单的程序,它有一个函数 start() 等待用户输入一些东西(使用无限循环)并将它存储在队列中。 start() 在单独的线程中运行。用户输入某个值后,队列的大小在 main 中保持为零。队列如何同步?
代码:source.cpp

#include <iostream>
#include "kl.h"

using namespace std;

int main()
{
    std::thread t1(start);
    while (1)
    {
        if (q.size() > 0)
        {
            std::cout << "never gets inside this if\n";
            std::string first = q.front();
            q.pop();
        }           
    }
    t1.join();
}

代码:kl.h

#include <queue>
#include <iostream> 
#include <string>

void start();
static std::queue<std::string> q;

代码:kl.cpp

#include "kl.h"
using namespace std;

void start()
{
    char i;
    string str;
    while (1)
    {
        for (i = 0; i <= 1000; i++)
        {
            //other stuff and str input
            q.push(str);
        }

    }
}

最佳答案

您的代码包含 race - 我崩溃了;两个线程都可能修改共享队列。 (此外,您正在使用 char i 循环获取高达 1000 的值 - 可能不是一个好主意。)

您应该使用 std::mutex 来保护您的共享队列,并使用 std::condition_variable通知有理由检查队列。

具体来说,您应该考虑以下内容(这对于您的 a producer consumer 情况很常见):

  1. 仅在持有互斥量时访问队列。

  2. 使用条件变量通知您已将某些内容推送到其中。

  3. 使用条件变量指定何时有继续处理的点的条件。

这里是你的代码的重写:

#include <iostream>
#include <queue>
#include <thread>
#include <condition_variable>
#include <mutex>

using namespace std;

std::queue<std::string> q;
std::mutex m;
std::condition_variable cv;

void start()
{
    string str;
    for (std::size_t i = 0; i <= 1000; i++) {
        //other stuff and str input
        std::cout << "here" << std::endl;
        std::unique_lock<std::mutex> lk(m);
        q.push(str);
        lk.unlock();
        cv.notify_one();
    }
}

int main()
{
    std::thread t1(start);
    for (std::size_t i = 0; i <= 1000; i++)
    {
        std::unique_lock<std::mutex> lk(m);
        cv.wait(lk, []{return !q.empty();});
        std::string first = q.front();
        q.pop();    
    }
    t1.join();
}

关于c++ - 两个线程之间的同步队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39663061/

相关文章:

c++ - 为什么 sleep() 会导致换行?

C++从 vector 中删除指针导致堆错误

multithreading - 多线程能提高性能吗?如何?

c++ - C++ 2011 中的 nextafter 与 nexttoward 函数?

c++ - 静态链接库时,出现链接器错误 : cannot find -lgcc_s

c++ - 为什么 CPP 中 WaitForSingleObject 函数的这两种不同行为

c# - Thread.Sleep(2500) 与 Task.Delay(2500).Wait()

c# - "A reference to a volatile field will not be treated as volatile"含义

c++11 - C++中如何获取一组字符串中最长的字符串

c++11 限制允许的模板参数类型的首选方法