初探C++11 Thread,初探c11thread

來源:互聯網
上載者:User

初探C++11 Thread,初探c11thread
Thread

 

開啟一個線程

 

使用c++11開啟一個線程是比較簡單的,如下:

 

#include<iostream>#include<thread>using namespace std;void hello(){    cout<<"hello kitty"<<endl;}int main(){    std::thread t(hello);     t.join();     return 0;}


輸出結果:

 

 

 

 


 

也可以通過函數對象的方式

 

#include<iostream>#include<thread>using namespace std;class Say_hello{public:    void operator()(){cout<<"hello";}};int main(){    Say_hello hello;    std::thread t(hello);    t.join();    return 0;}

輸出結果:

 

 

 

帶參數的函數

 

當函數自身有參數時,形參可以直接寫在開啟線程的函數參數的後面,如:

thread  t( function , t1 , t2 , ...)

比如說下面這2個例子

 

#include<iostream>#include<thread>using namespace std;class Say_hello{public:    enum {times = 2};    void operator()(int n = times)    {        for(int i=0;i!=n;i++)            cout<<"hello"<<endl;    }};int main(){    Say_hello hello;    std::thread t(hello);    t.join();    return 0;}


不帶參數時,輸出結果為:


 

 

 

帶參數時,輸出結果為:

int main(){    Say_hello hello;    std::thread t(hello,5);    t.join();    return 0;}


 

 

 

鎖的實現

 

 

多線程為了實現安全執行緒,當訪問共用資料時,要避免幾個線程同時訪問,以免造成競爭條件(race condition)

下面舉了一個簡單的例子,用鎖來實現同步。

 

 

 

一共10張票,開4個線程來賣票。

 

#include<iostream>#include<thread>#include<mutex>using namespace std;int tickets_count = 10;mutex a_mutex;void sale(){    lock_guard<mutex> guard(a_mutex);    //a_mutex.lock();    while(tickets_count>0)    {       cout<<tickets_count--<<endl;    }     //a_mutex.unlock();}int main(){    std::thread t1(sale);    std::thread t2(sale);    std::thread t3(sale);    std::thread t4(sale);    t1.join();    t2.join();    t3.join();    t4.join();    return 0;}

如果不加鎖,可能造成重複,輸出混亂(std::out 也不是安全執行緒)

通過對臨界區加鎖來盡量實現安全執行緒。

 

輸出結果為:



 

 

 


 

 


11秋福師《學前兒童科學教育》線上作業一

一、單選題(共 20 道試題,共 40 分。) 得分:40V 1. 下列屬於評價幼兒科學探究能力的是:()
A. 吸收精神
B. 堅持性
C. 獨立性
D. 對材料的操作、工具的使用
正確答案:D 滿分:2 分 得分:2
2. 協助學前兒童學習把物體按兩套標準進行分類,宜放在哪個年齡階段進行
A. 2~3歲
B. 3~4歲
C. 4~5歲
D. 5~6歲
正確答案:D 滿分:2 分 得分:2
3. 在兒童學科學的諸要素中,幼兒學科學的物質前提是
A. 探索態度
B. 探索對象
C. 探索過程
D. 探索結果
正確答案:B 滿分:2 分 得分:2
4. 學前兒童學科學的動力是( )。
A. 探索態度
B. 探索過程
C. 探索對象
D. 探索結果
正確答案:A 滿分:2 分 得分:2
5. 在觀察前依據所需觀察的目標制定觀察核對錶,調查者根據觀察到的事件或行為,對照表中的各項目逐條檢核,並在符合的條目上做出記號並進行評定的是
A. 觀察核對
B. 行為核對
C. 觀察評價
D. 行為評價
正確答案:B 滿分:2 分 得分:2
www.aopengzuoye.com/thread-47289-1-1.html
 
C/c++的多線程編程怎學習?還有就是誰可以給我一個C/C++的庫文檔?了

對於剛入門,你可以玩玩pthread庫
在codeblocks使用pthread庫編寫多線程應用,很方便啊
現在c++11語言內建就支援多執行緒模式

C/C++感興趣的歡迎來百度codeblocks貼吧
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.