引发异常:调用方法front时发生读取访问冲突



当我尝试从队列中获取第一个项目时,我出现了错误。

引发异常:读取访问冲突。**std::deque<int,std::分配器>::front**(…(返回0xDDDDDE9。

发生错误时,队列不是空的

#include <iostream>
#include <queue>
#include <thread>
#include<mutex>
#include<chrono>
using namespace std;
int total;
queue<int> ox;
mutex mtx, mtx1;
void push(int x) {
mtx1.lock();
ox.push(x);
mtx1.unlock();
}
bool pop(int x) {
if (ox.size() == 0) this_thread::sleep_for(chrono::milliseconds(1));
if (ox.size() != 0) {
mtx.lock();
x = ox.front();
ox.pop();
mtx.unlock();
return true;
}
if (ox.size() == 0) {
return false;
}
return false;
}
void producer() {
for (int i = 0; i < 1024 * 1024 * 4; i++) push(1);
}
void consumer() {
int sum = 0;
for (int i = 0; i < 1024 * 1024 * 4; i++) {
int k;
if (pop(k)) sum += k;
}
total += sum;
}
int main()
{
thread th1(producer);
thread th2(consumer);
th1.join();
th2.join();
cout << total;
}

每个线程都有一个单独的std::mutex,这意味着实际上根本没有互斥。您需要对两个线程使用相同的互斥对象。

您的pop函数中也有一个拼写错误,应该是bool pop(int& x)

您不应该直接调用mtx.lock()mtx.unlock(),最好使用std::unique_lock(或标准库中定义的其他锁之一(,这样可以确保互斥锁在超出范围时始终解锁,例如:

void push(int x) {
std::unique_lock<std::mutex> lock(mtx);
ox.push(x);
}
bool pop(int& x) {
if (ox.size() == 0) this_thread::sleep_for(chrono::milliseconds(1));
if (ox.size() != 0) {
std::unique_lock<std::mutex> lock(mtx);
x = ox.front();
ox.pop();
return true;
}
if (ox.size() == 0) {
return false;
}
return false;
}
#include <iostream>
#include <queue>
#include <thread>
#include<mutex>
#include<chrono>
using namespace std;
long long total;
queue<int> ox;
mutex mtx;
void push(int x) {
mtx.lock();
ox.push(x);
mtx.unlock();
}
bool pop(int& x) {
mtx.lock();
if (ox.size() == 0) this_thread::sleep_for(chrono::milliseconds(1));
if (ox.size() != 0) {
x = ox.front();
ox.pop();
mtx.unlock();
return true;
}
mtx.unlock();
return false;
}
void producer() {
for (int i = 0; i < 1024 * 1024 * 4; i++) push(1);
}
void consumer() {
for (int i = 0; i < 1024 * 1024 * 4; i++) {
int k;
if (pop(k)) total += k;
}
}
int main()
{
thread th1(producer);
thread th2(consumer);
th1.join();
th2.join();
cout << total;
}

您使用引用变量的方式不对。将其替换为指针。

最新更新