溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C++中怎么實現一個多線程計數器

發布時間:2021-08-09 15:06:32 來源:億速云 閱讀:299 作者:Leah 欄目:編程語言

C++中怎么實現一個多線程計數器,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

以計數器實現為例子,演示了多線程計數器的實現技術方法,代碼如下:

//目的: 測試利用C++ 11特性實現計數器的方法 //操作系統:ubuntu 14.04 //publish_date: 2015-1-31 //注意所使用的編譯命令: g++ -Wl,--no-as-needed -std=c++0x counter.cpp -lpthread #include <iostream> #include <atomic> #include <thread> #include <vector>  using namespace std;  atomic_int Counter(0); int order[400];  void work(int id) {     int no;     for(int i = 0; i < 100; i++) {         no = Counter++;         order[no] = id;     } }  int main(int argc, char* argv[]) {     vector<thread> threads;     //創建多線程訪問計數器     for (int i = 0; i != 4; ++i)         //線程工作函數與線程標記參數         threads.push_back(thread(work, i));     for (auto & th:threads)         th.join();     //最終的計數值     cout << "final :" << Counter << endl;     //觀察各線程的工作時序     for(int i = 0; i < 400; i++)         cout << "[" << i << "]=" << order[i] << " ";     return 0; }

注意編譯命令的參數,尤其,-lpthread

否則,若無該鏈接參數,則編譯不會出錯,但會發生運行時錯誤:

terminate called after throwing an instance of &lsquo;std::system_error&rsquo;

what(): Enable multithreading to use std::thread: Operation not permitted

看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

c++
AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女