若有安裝色情守門員,可用無界、自由門等軟件瀏覽伊莉。或使用以下網址瀏覽伊莉: http://www.eyny.com:81/index.php
本帖最後由 bkmambaaaa 於 2015-1-9 12:34 AM 編輯
試試看:
- #include <iostream> // cout
- #include <thread> // thread, this_thread::sleep_for
- #include <chrono> // chrono::seconds
- #include <functional> // ref
- #include <mutex> // mutex
- using namespace std;
- mutex mtx_stdout; // mutex for stdout
- class Bomber {
- protected:
- int bombcount;
- mutex mtx_bc; // mutex for bombcount;
- public:
- Bomber() : bombcount(0) {}
- void boom();
- void bomb_print();
- static void time(Bomber &b);
- };
- void Bomber::boom() {
- if(0==bombcount) {
- mtx_bc.lock();
- ++bombcount;
- mtx_bc.unlock();
-
- mtx_stdout.lock();
- cout << "Bomb set...bombcount = " << bombcount << '\n';
- mtx_stdout.unlock();
- thread (time,ref(*this)).detach();
- }
- }
- void Bomber::bomb_print() {
- mtx_bc.lock();
- --bombcount;
- mtx_bc.unlock();
- mtx_stdout.lock();
- // do some printing here...
- cout << "BOOM! bombcount = " << bombcount << '\n';
- mtx_stdout.unlock();
- }
- void Bomber::time(Bomber &b) {
- this_thread::sleep_for(chrono::seconds(3));
- b.bomb_print();
- }
- int main() {
- Bomber b;
- b.boom();
- for(;;) {} // infinite loop
- }
複製代碼 1. thread 可以丟進一個 static member function,如我的例子。另外,你可以用 std::ref 把自身物件包起來傳進 thread 和 static member function 之內,這樣就可以在內部使用物件的成員。
2. join() 是母 thread 要等子 thread 才需要呼叫,意思是暫停一切動作,等待子 thread 完成。因為放下炸彈後,你應該還可以走來走去,所以母 thread 不需要等子 thread,直接呼叫 detach() 切斷關係,讓子 thread 獨立運作,完成自己釋放資源。
建議加上 mutex 的使用。你的 bombcount 會被多個 thread 存取,所以最好存取前保護起來。另外標準輸出裝置(螢幕的 console 畫面)也最好用全域的 mutex 保護起來。
先這樣,有問題再說。
附帶一題 thread 是 c++11 的功能,其他版友如果要編譯需要用 VS 2012 以後的,或者其他比較新的編譯器。
... |