2
假設我有一個類A
中的2個線程方法。其中一個線程一直在運行,並檢查是否設置了成員變量。如果此成員變量設置爲true,則應啓動另一個線程。第二個線程mThread2
通過檢查變量mRunThread2
自行停止。布爾變量的線程同步
現在的問題是:是否必須共同排除布爾變量?寫入變量需要多個彙編指令,所以在這一點上我需要一個同步。
class A {
public:
A() : mRunThread1(true) {
mThread1 = std::thread(&A::DoWork1(), this);
}
~A() {
mRunThread1 = false;
}
void Start2() { mRunThread2 = true; }
void Stop2() { mRunThread2 = false; }
private:
bool mRunThread1;
bool mRunThread2;
std::thread mThread1;
std::thread mThread2;
void DoWork1() {
while (mRunThread1) {
bool lastState = false;
if (mRunThread2 && !lastState) {
if (mThread2.joinable()) mThread2.join();
mThread2 = std::thread(&A::DoWork2(), this);
}
lastState = mRunThread2;
}
}
void DoWork2() {
while (mRunThread2) {
:::
}
}
};
如果還有其他問題,請點擊[問問題](http://stackoverflow.com/questions/ask)按鈕。我已經走了,回頭追加了新的問題以保持正確。 – Mgetz