这是一个简单的程序,它有一个函数 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 情况很常见):
仅在持有互斥量时访问队列。
使用条件变量通知您已将某些内容推送到其中。
使用条件变量指定何时有继续处理的点的条件。
这里是你的代码的重写:
#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/