gpt4 book ai didi

c++ - Visual Studio 2013 标准::线程

转载 作者:搜寻专家 更新时间:2023-10-31 01:41:10 24 4
gpt4 key购买 nike

以下程序在使用 Visual Studio 2013 编译时会出现一些奇怪的编译/运行时行为:

#include "stdafx.h"
#include <thread>
#include <chrono>
#include <iostream>

int main()
{

{//works
std::thread([](){
std::cout << " thread running1\n";
});
}

{//compile but synstax error exist
auto func = [](){
std::cout << " thread running2\n";
};

std::thread(fun); //fun is not defined
}


{//compile, see next block for mystery compile error
auto func = [](){
std::cout << " thread running2\n";
};

std::thread tmp(func);
}

{//does not compile and don't know why
auto func = [](){
std::cout << " thread running2\n";
};

std::thread(func); //error C2371: 'func' : redefinition; different basic types
}

return 0;
}

当这个程序运行时,可能会因为线程之间存在竞争条件而崩溃。主线程可能会在其他线程之前结束。

有人知道为什么第二个 block 和最后一个 block 不起作用吗?

最佳答案

{//compile but synstax error exist
auto func = [](){
std::cout << " thread running2\n";
};

std::thread(fun); //fun is not defined
}

这里没有语法错误,std::thread(fun)默认构造了一个名为funstd::thread对象。

最后一个block的错误也是同样的原因

std::thread(func); //error C2371: 'func' : redefinition; different basic types

您正在尝试默认构造一个名为 funcstd::thread 对象,这是一个错误,因为同名的 lambda 已存在于同一作用域中.要将 lambda 传递给 thread 构造函数,请改用大括号

 std::thread{func};

现在,在您进行这些更改后,您的代码将编译但会在运行时失败,因为 block 1、3 和 4 中的线程对象都将调用 std::terminate(的当然,当第一个线程对象调用 std::terminate 时,您的程序将终止,因此其他两个执行此操作是有争议的)。

发生这种情况的原因是您在所有 3 个 block 中都有可连接 线程,并且如果 destructor这样的线程对象运行,std::terminate will be called .为避免这种情况,您必须调用 thread::join(您也可以调用 thread::detach,但不要那样做)。

例如

{//works
std::thread([](){
std::cout << " thread running1\n";
}).join();
}

Live demo

关于c++ - Visual Studio 2013 标准::线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28804368/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com