C / C++ のマルチスレッド,排他制御の質問です. 以下のコードをベースに ”AAA”と”BBB”を交互に出力するにはどのようにすれば良いでしょうか?
C / C++ のマルチスレッド,排他制御の質問です. 以下のコードをベースに ”AAA”と”BBB”を交互に出力するにはどのようにすれば良いでしょうか? ロックなどを上手く使えずに困っています. 有識者の方,よろしくお願い致します. #include <iostream> #include <thread> #include <mutex> using namespace std; mutex mtx; void ThreadA() { while (true) { mtx.lock(); cout << "AAA" << endl; mtx.unlock(); } } void ThreadB() { while (true) { mtx.lock(); cout << "BBB" << endl; mtx.unlock(); } } int main() { std::thread th_a(ThreadA); std::thread th_b(ThreadB); th_a.join(); th_b.join(); return 0; }
ベストアンサー
stdのcondition_variableを使って、実装できました。 多分、排他制御での実装の課題なんでしょう。 mutexだけでも、実装可能かもしれません。 #include <iostream> #include <thread> #include <mutex> #include <condition_variable> using namespace std; std::mutex mtx; int statusA = 0; int statusB = 0; bool avaiableA() {return statusA!=0;} bool avaiableB() {return statusB!=0;} std::condition_variable cvA; std::condition_variable cvB; void ThreadA() { while (true) { std::unique_lock<std::mutex> lck(mtx); cvA.wait(lck, avaiableA); cout << "AAA" << endl; statusA=0; statusB=1; cvB.notify_one(); } } void ThreadB() { while (true) { std::unique_lock<std::mutex> lck(mtx); cvB.wait(lck, avaiableB); cout << "BBB" << endl; statusB=0; statusA=1; cvA.notify_one(); } } int main() { std::thread th_a(ThreadA); std::thread th_b(ThreadB); statusA=1; cvA.notify_one(); th_a.join(); th_b.join(); return 0; }
2つのmutexを交互にlock,unlockすれば可能ですね。 課題のようですから、ソースはアップしません。 condition_variableのコードでは、課題的には△となるでしょう。
質問者からのお礼コメント
ありがとうございます! 課題ではないのでcondition_variableでも問題ありません。 waitやnotify_one()など上手く使いこなせるように頑張ります。 大変参考になりました。
お礼日時:6/26 2:25