C 多執行緒基礎學習筆記(七)

2022-07-19 09:48:17 字數 1192 閱讀 5408

一、std::async和std::future的用法

std::async是乙個函式模板,std::future是乙個類模板

std::async(std::launch::async, mythread);如果std::async()的第乙個引數改成std::lauch::deferred,那麼執行緒不會被馬上執行,而是延遲到std::future的wait()或者get()函式呼叫時才執行執行緒的入口函式。實際上,並沒有建立

子執行緒,而只是在主函式中呼叫了入口函式。

二、std::packaged_task的用法

std::packaged_task是乙個類模板,模板引數各種可呼叫物件,通過它把各種可呼叫物件包裝起來,方便作為執行緒入口函式來呼叫
1 #include 2 #include 3 #include 4 #include 5

6using

namespace

std;78

int fun(int

val)915

intmain()

16

三、std::promise的用法

std::promise是乙個類模板,能夠在某個執行緒中給它賦值,然後可以在其他執行緒中,在將來的某個時刻,可以把這個值取出來。

1 #include 2 #include 3 #include 4 #include 5

6using

namespace

std;78

void mythread1(std::promise &pro, int

val)918

1920

void mythread2(std::future &getful)

2127

intmain()

28

std::ref 用於包裝按引用傳遞的值。

C 多執行緒學習筆記七

task int task task.factory.startnew task.wait console.writeline task.result task int task task.factory.startnew var task2 task.continuewith int t cons...

C 多執行緒基礎學習筆記(三)

一 detach 大坑 由監檢視可知,實參n和形參a的位址並不同,所以實際是值傳遞,並因此最好不要用引用,直接用值傳遞就行了。主線程的str m和str的位址卻相同,那麼當子執行緒和主線程分離時,就會出現問題。這裡講乙個改進的方法,把形參char str改成const string str,即把傳進...

C 學習 多執行緒程式設計 多執行緒基礎

c 內建了對多執行緒程式設計的支援功能,所以相對於其他語言在多執行緒方面的問題,c 這裡就已經最小化或者不復存在。在.net framework 4.0中,c 中新增了兩個與多執行緒應用程式相關的重要功能 tpl 任務執行並行庫 和plinq 並行linq 兩者都提供對並行程式設計的支援,都可以利用...