thread1
機能は出力が1 2 1 2
が、私のUbuntuでその1 1 1
ある私のMacではC++のスレッドが
#include <iostream>
#include <fstream>
#include <thread>
#include <condition_variable>
#include <queue>
std::condition_variable cv;
std::mutex mu;
std::queue<int> queue;
bool ready;
static void thread1() {
while(!ready) {std::this_thread::sleep_for(std::chrono::milliseconds(10));}
while(ready && queue.size() <= 4) {
std::unique_lock<std::mutex> lk(mu);
cv.wait(lk, [&]{return !queue.empty();});
queue.push(2);
}
}
int main() {
ready = false;
std::thread t(thread1);
while(queue.size() <= 4) {
{
std::lock_guard<std::mutex> lk(mu);
queue.push(1);
}
ready = true;
cv.notify_one();
}
t.join();
for(int i = 0; i <= queue.size(); i++) {
int a = queue.front();
std::cout << a << std::endl;
queue.pop();
}
return 0;
}
を実行し得るように見えることはありません実行されません。私はg++ -std=c++11 -pthread -o thread.out thread.cpp && ./thread.out
でコンパイルしています。何か不足していますか?
メインループが再度ロックする前に、スレッド1がミューテックスを取得できる保証はありません。それはマルチスレッド化の仕方であり、予測できないことがあります。 –
しかし私は、thread1の条件変数が、mainとthread1の両方の待機と同期でmutexをロックすると考えました。同期を実行して順番に実行するにはどうすればよいですか? – Seph
あなたは競争状態にあります。 'thread1'は' queue.size() 'を実行でき、' main'は 'queue.push(1)'を実行し、動作は未定義です。 – GManNickG