线程安全和 std::move
Thread safety and std::move
前言:
当我输入新代码时,我会不假思索(出于习惯)将我的函数声明为 pass-by-reference-to-const,有时不得不返回并更改它当我意识到这不是我想做的。
我正在编写一个工作线程 class,它 运行 无限期地运行,并被馈送字符串(来自另一个线程)进行处理。当我意识到我已经将函数声明为 pass-by-ref 时,我回去将其更改为 pass-by-value,因为线程安全。
但是,由于我想尽可能地提高速度和效率,所以我先停下来探索各种选择。我写了一个小测试例程 - 发现我对一些关键概念很模糊。
进入正题:我先把测试代码写在下面,没有注释行:
// std::thread _thread(workthread, move(str)); // Thread safe (contents are moved)
因此,暂时忽略该行。
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include <atomic>
std::atomic<bool> done = false;
void workthread(const std::string &str)
{
std::string &s = const_cast<std::string &>(str);
s = "Work Thread"; // test to see if this changes the main thread's string
}
// This just watches for <enter> on the keyboard in order to quit the program.
void quitmonitor()
{
std::getchar();
done = true;
}
int main(int argc, char **argv)
{
std::thread _monitor(quitmonitor);
std::string str("Main Thread");
std::thread _thread([&]{workthread(std::move(str));}); // Not thread safe (address is copied)
// std::thread _thread(workthread, move(str)); // Thread safe (contents are moved)
const auto minlen(str.length());
const auto maxlen(minlen ? minlen*2 : 15);
bool going_up = true;
while (!done) {
if (going_up)
str.push_back('+');
else
str.pop_back();
if (str.length() == minlen)
going_up = true;
if (str.length() == maxlen)
going_up = false;
std::cout << str << "\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
_thread.join();
_monitor.join();
}
main()
所做的只是创建一个字符串"Main Thread",并将其移动到线程函数void workthread(const std::string &)
。线程函数然后更改左值的数据和 returns。 main 继续执行一个循环,该循环仅将其本地字符串打印到控制台(带有一些额外的视觉效果,以便于在屏幕上看到发生的事情)。这是输出:
所以,它没有像我预期的那样工作。我原以为线程实例化会"move"str
给线程函数(清空它在进程中的数据),线程给函数的字符串参数赋值不会有任何影响。但显然它确实如此,正如输出所证明的那样。
这一定与我用 lambda 构造 _thread
有关:
std::thread _thread([&]{workthread(std::move(str));}); // Not thread safe (address is copied)
然后我将实例化更改为:
std::thread _thread(workthread, move(str)); // Thread safe (contents are moved)
它按预期工作:
Q1: 为什么这两个实例,lambda 与 bind(我猜?),产生不同的结果?
问题 2: 我是否真的通过将其声明为 传递引用 来为自己购买任何东西?
我应该指出,实际程序对时间要求很高,旨在 运行 在专用服务器上多年不间断。我正在努力使软件的开销尽可能低,以确保它可以保持同步(与外部时钟),而不是累积时间错误。
std::thread _thread([&]{workthread(std::move(str));});
创建 _thread
时,它会调用您的 lambda 函数,该函数会调用 workthread(std::move(str))
。请注意 std::move
实际上并没有做任何事情;它只是对右值引用的转换。您永远不会从 str
移动,您只是以迂回的方式将引用转换为 std::string&
并分配给它。
这也意味着您在 str
上存在数据竞争,因为主线程与 _thread
之间的访问不同步。
此代码从字符串中移出,但是:
std::thread _thread(workthread, move(str));
如果您查看 std::thread
's constructor(该列表中的 (3)),您会发现它 "copies" 是函数调用的参数;它大致调用:
workthread(decay_copy(std::move(str)))
这个 decay_copy
实际上确实从字符串移动,因为它 returns 按值:
template <class T>
std::decay_t<T> decay_copy(T&& v) { return std::forward<T>(v); }
这就是您看到 str
被移出的原因。但是,您的程序实际上依赖于未指定的行为,因为 - 从 std::string
移动后 - 字符串留在 "valid but unspecified state" 中(std::string
的 move constructor and move assignment operator)。你不能指望 str
被移动后是一个空字符串。
前言: 当我输入新代码时,我会不假思索(出于习惯)将我的函数声明为 pass-by-reference-to-const,有时不得不返回并更改它当我意识到这不是我想做的。
我正在编写一个工作线程 class,它 运行 无限期地运行,并被馈送字符串(来自另一个线程)进行处理。当我意识到我已经将函数声明为 pass-by-ref 时,我回去将其更改为 pass-by-value,因为线程安全。
但是,由于我想尽可能地提高速度和效率,所以我先停下来探索各种选择。我写了一个小测试例程 - 发现我对一些关键概念很模糊。
进入正题:我先把测试代码写在下面,没有注释行:
// std::thread _thread(workthread, move(str)); // Thread safe (contents are moved)
因此,暂时忽略该行。
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include <atomic>
std::atomic<bool> done = false;
void workthread(const std::string &str)
{
std::string &s = const_cast<std::string &>(str);
s = "Work Thread"; // test to see if this changes the main thread's string
}
// This just watches for <enter> on the keyboard in order to quit the program.
void quitmonitor()
{
std::getchar();
done = true;
}
int main(int argc, char **argv)
{
std::thread _monitor(quitmonitor);
std::string str("Main Thread");
std::thread _thread([&]{workthread(std::move(str));}); // Not thread safe (address is copied)
// std::thread _thread(workthread, move(str)); // Thread safe (contents are moved)
const auto minlen(str.length());
const auto maxlen(minlen ? minlen*2 : 15);
bool going_up = true;
while (!done) {
if (going_up)
str.push_back('+');
else
str.pop_back();
if (str.length() == minlen)
going_up = true;
if (str.length() == maxlen)
going_up = false;
std::cout << str << "\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
_thread.join();
_monitor.join();
}
main()
所做的只是创建一个字符串"Main Thread",并将其移动到线程函数void workthread(const std::string &)
。线程函数然后更改左值的数据和 returns。 main 继续执行一个循环,该循环仅将其本地字符串打印到控制台(带有一些额外的视觉效果,以便于在屏幕上看到发生的事情)。这是输出:
所以,它没有像我预期的那样工作。我原以为线程实例化会"move"str
给线程函数(清空它在进程中的数据),线程给函数的字符串参数赋值不会有任何影响。但显然它确实如此,正如输出所证明的那样。
这一定与我用 lambda 构造 _thread
有关:
std::thread _thread([&]{workthread(std::move(str));}); // Not thread safe (address is copied)
然后我将实例化更改为:
std::thread _thread(workthread, move(str)); // Thread safe (contents are moved)
它按预期工作:
Q1: 为什么这两个实例,lambda 与 bind(我猜?),产生不同的结果?
问题 2: 我是否真的通过将其声明为 传递引用 来为自己购买任何东西?
我应该指出,实际程序对时间要求很高,旨在 运行 在专用服务器上多年不间断。我正在努力使软件的开销尽可能低,以确保它可以保持同步(与外部时钟),而不是累积时间错误。
std::thread _thread([&]{workthread(std::move(str));});
创建 _thread
时,它会调用您的 lambda 函数,该函数会调用 workthread(std::move(str))
。请注意 std::move
实际上并没有做任何事情;它只是对右值引用的转换。您永远不会从 str
移动,您只是以迂回的方式将引用转换为 std::string&
并分配给它。
这也意味着您在 str
上存在数据竞争,因为主线程与 _thread
之间的访问不同步。
此代码从字符串中移出,但是:
std::thread _thread(workthread, move(str));
如果您查看 std::thread
's constructor(该列表中的 (3)),您会发现它 "copies" 是函数调用的参数;它大致调用:
workthread(decay_copy(std::move(str)))
这个 decay_copy
实际上确实从字符串移动,因为它 returns 按值:
template <class T> std::decay_t<T> decay_copy(T&& v) { return std::forward<T>(v); }
这就是您看到 str
被移出的原因。但是,您的程序实际上依赖于未指定的行为,因为 - 从 std::string
移动后 - 字符串留在 "valid but unspecified state" 中(std::string
的 move constructor and move assignment operator)。你不能指望 str
被移动后是一个空字符串。