【发布时间】:2017-12-18 18:17:23
【问题描述】:
我刚刚开始学习 C++ 中的多线程...
t1 和 t2 有区别吗?
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mutexCout;
//prints the value of x, and then increments it
//param: int value to display and increment
void foo (int& x)
{
std::lock_guard<std::mutex> guard_(mutexCout);
std::cout << "x is " << x << "\n";
++x;
}
//testing different ways to call a function with reference
int main()
{
int x = 5;
//is t1 different from t2???
std::thread t1 ([&] {foo(x)};
std::thread t2 (foo, std::ref(x));
{
std::lock_guard<std::mutex> guard_(mutexCout);
std::cout << "x is " << x << "\n";
}
//added after posting the question
t1.join();
t2.join();
return 0;
}
【问题讨论】:
-
这个问题最好在Code Review 提出。我会选择更简单的构造,即 t2。 t1 需要一个特殊的语言特性 (lambda),如果没有明显的好处,为什么要使用它。
-
@zett42,我会说 t1 初始化程序是简单的初始化程序。 (忽略语法错误)t2 需要一个特殊的库功能(
std::ref),如果没有明显的好处,为什么要使用它呢?
标签: multithreading c++11 lambda