久久久久久久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 排序功能對列表進行排序)
主站蜘蛛池模板: 日本色视频 | 天天干在线观看 | 在线观看视频一区 | 91精品国产成人www | 91福利在线观看 | 国产精品一品二区三区的使用体验 | 天天操网站 | avxxxxx| 免费av一区 | 成人精品| 污视频网站在线观看 | 日韩欧美精品一区 | 可以免费看av的网站 | 欧美亚洲视频 | 亚洲第一第二区 | 亚洲免费看片 | 亚洲iv一区二区三区 | 日本不卡免费 | 中文字幕欧美日韩 | 少妇一级淫片免费放 | av日韩在线播放 | 午夜一级视频 | 国产免费黄色片 | www.久草.com | 国产91在线播放 | 9.1成人免费看片 | 国产黄在线观看 | 欧美18免费视频 | 三级黄色片网站 | 色婷婷影视| 黄色在线观看网址 | 超碰在线网站 | 天天色天天干天天 | av在线免费网站 | av一区二区在线观看 | 美日韩一区二区三区 | 中文字幕国产在线 | 性色av一区二区三区 | 韩国理论在线 | 视频一区二区在线播放 | 日本中文字幕一区 |