我有一个消费者和两个生产者。 当我同时产生两个生产者时,他们似乎互相锁定,因为我们看到的第一个值分别是223和889。unique_lock跨线程
有人能解释一下这里发生了什么吗?
#include<vector>
#include<thread>
#include<iostream>
#include<mutex>
#include<chrono>
#include <condition_variable>
using namespace std;
vector<double>testvec;
mutex mtx;
condition_variable cv;
class Base
{
public:
Base() {};
void dosomething();
int i;
};
void Base::dosomething()
{
while(1)
{
std::unique_lock<std::mutex> ulck(mtx);
testvec.push_back(i);
ulck.unlock();
cv.notify_all();
i++;
std::this_thread::sleep_for (std::chrono::milliseconds(i));
}
};
class Derived1 : public Base
{
public:
Derived1() {i = 222;}
};
class Derived2 : public Base
{
public:
Derived2() {i = 888;}
};
class Consumer
{
public:
Consumer() {}
void dostuff();
};
void Consumer::dostuff()
{
while(1)
{
std::unique_lock<std::mutex> ulck(mtx); //locks shared data
cv.wait(ulck);
cout<<"last value: "<<testvec.back()<<endl;
ulck.unlock();
}
}
int main(int argc, char ** argv)
{
Derived1 derived1;
Derived2 derived2;
Consumer c;
std::thread t1(&Derived1::dosomething, &derived1);
std::thread t2(&Derived2::dosomething, &derived2);
std::thread t3(&Consumer::dostuff, &c);
t1.join();
t2.join();
t3.join();
}
output is:
last value: 223
last value: 224
last value: 225
last value: 889
last value: 226
last value: 227
last value: 228
last value: 229
last value: 890
last value: 230
expected output:
last value: 888 (or 222)
last value: 222 (or 888)
last value: 223
...
什么错输出? – fghj
所以每次创建新数据。消费者进行计算并将其打印出来进行筛选。这没有发生。它的锁只是被两个派生类抓住,但没有做任何事情。 – acv17
@ user1034749,我在运行的实际代码中重新创建了相同的问题。希望这是有道理的。有任何想法吗? – acv17