久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

指針和引用作為線程參數的區別

Difference between pointer and reference as thread parameter(指針和引用作為線程參數的區別)
本文介紹了指針和引用作為線程參數的區別的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

示例如下:

#include<iostream>
#include<thread>
using namespace std;

void f1(double& ret) {
   ret=5.;
}

void f2(double* ret) {
   *ret=5.;
}

int main() {
   double ret=0.;
   thread t1(f1, ret);
   t1.join();
   cout << "ret=" << ret << endl;
   thread t2(f2, &ret);
   t2.join();
   cout << "ret=" << ret << endl;   
}

輸出是:

ret=0
ret=5

使用 gcc 4.5.2 編譯,帶有和不帶有 -O2 標志.

Compiled with gcc 4.5.2, with and without -O2 flag.

這是預期的行為嗎?

這個程序是免費的數據競爭嗎?

Is this program data race free?

謝謝

推薦答案

std::thread 的構造函數推導參數類型并按值存儲它們的副本.這需要確保參數對象的生命周期至少與線程的生命周期相同.

The constructor of std::thread deduces argument types and stores copies of them by value. This is needed to ensure the lifetime of the argument object is at least the same as that of the thread.

C++ 模板函數參數類型推導機制從 T& 類型的參數推導類型 T.std::thread 的所有參數都被復制,然后傳遞給線程函數,以便 f1()f2() 始終使用該副本.

C++ template function argument type deduction mechanism deduces type T from an argument of type T&. All arguments to std::thread are copied and then passed to the thread function so that f1() and f2() always use that copy.

如果您堅持使用引用,請使用 boost::ref()std::ref() 包裝參數:

If you insist on using a reference, wrap the argument using boost::ref() or std::ref():

thread t1(f1, boost::ref(ret));

或者,如果您更喜歡簡單,請傳遞一個指針.這就是 boost::ref()std::ref() 在幕后為您做的事情.

Or, if you prefer simplicity, pass a pointer. This is what boost::ref() or std::ref() do for you behind the scene.

這篇關于指針和引用作為線程參數的區別的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

What is the fastest way to transpose a matrix in C++?(在 C++ 中轉置矩陣的最快方法是什么?)
Sorting zipped (locked) containers in C++ using boost or the STL(使用 boost 或 STL 在 C++ 中對壓縮(鎖定)容器進行排序)
Rotating a point about another point (2D)(圍繞另一個點旋轉一個點 (2D))
Image Processing: Algorithm Improvement for #39;Coca-Cola Can#39; Recognition(圖像處理:Coca-Cola Can 識別的算法改進)
How do I construct an ISO 8601 datetime in C++?(如何在 C++ 中構建 ISO 8601 日期時間?)
Sort list using STL sort function(使用 STL 排序功能對列表進行排序)
主站蜘蛛池模板: h视频在线免费观看 | 成年人黄色免费视频 | 一级视频黄色 | 亚洲精品电影在线 | 中文字幕一区二区三区四区 | 99精品久久久 | 午夜影院在线观看 | 亚洲在线中文字幕 | www日本在线播放 | 韩国主播午夜大尺度福利 | 五月天天丁香婷婷在线中 | 性做久久久久久免费观看欧美 | 不用播放器看的av | 亚洲最色网站 | 日一日操一操 | 成人妇女免费播放久久久 | 国产福利在线视频 | 精品九九九| 国产免费让你躁在线视频 | 2018天天干天天操 | 国产欧美在线观看 | 久久久999成人 | 精品国产91亚洲一区二区三区www | 日本激情视频网 | 久热精品免费 | 亚洲精品国产偷自在线观看 | 国产女人叫床高潮大片免费 | 国产精品高潮呻吟久久av黑人 | 日韩精品一区二区三区视频播放 | 一区二区三区国产视频 | 香蕉视频黄色 | 欧美精品在线一区二区三区 | 国产在线观看一区二区 | 中文字幕亚洲一区二区三区 | xx性欧美肥妇精品久久久久久 | 日本不卡视频在线播放 | 日韩高清中文字幕 | 欧美黄视频 | av一二三区 | 成人国产精品久久久 | 成人精品久久久 |