gpt4 book ai didi

c++ - std::async 在 linux 上的 gcc 4.7 中被破坏了吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:44:52 26 4
gpt4 key购买 nike

<分区>

在实际代码中使用它之前,我正在隔离地测试 std::async,以验证它是否在我的平台(即 ubuntu 12.10 64 位)上正常工作。

它有效(很少)并且通常只是挂起。如果它对您有用,请不要妄下结论。多试几次,估计会挂掉。

如果我删除 pthread_mutex 测试,它不会挂起。这是我可以重现挂起的最小代码。有什么原因不能将 C pthread 代码与 C++ 异步代码混合使用吗?

#include <iostream>
#include <pthread.h>
#include <chrono>
#include <future>
#include <iomanip>
#include <sstream>
#include <type_traits>

template<typename T>
std::string format_ns(T &&value)
{
std::stringstream s;
if (std::is_floating_point<T>::value)
s << std::setprecision(3);

if (value >= 1000000000)
s << value / 1000000000 << "s";
else if (value >= 1000000)
s << value / 1000000 << "ms";
else if (value >= 1000)
s << value / 1000 << "us";
else
s << value << "ns";
return s.str();
}

template<typename F>
void test(const std::string &msg, int iter, F &&lambda)
{
std::chrono::high_resolution_clock clock;
auto st = clock.now();

int i;
for (i = 0; i < iter; ++i)
lambda();
auto en = clock.now();
std::chrono::nanoseconds dur = std::chrono::duration_cast<
std::chrono::nanoseconds>(en-st);

std::cout << msg << format_ns(dur.count() / i) << std::endl;
}

int test_pthread_mutex()
{
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;

test("pthread_mutex_lock/pthread_mutex_unlock: ", 1000000000,
[&]()
{
pthread_mutex_lock(&m);
pthread_mutex_unlock(&m);
});

pthread_mutex_destroy(&m);

return 0;
}

int test_async()
{
test("async: ", 100,
[&]()
{
auto asy = std::async(std::launch::async, [](){});
asy.get();
});

return 0;
}

int main()
{
test_pthread_mutex();
test_async();
}

这是构建命令行:

g++ -Wextra -Wall  --std=c++11 -pthread mutexperf/main.cpp

没有构建输出消息。

这是 g++ -v 的输出

Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.7/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.7.2-2ubuntu1' --with-bugurl=file:///usr/share/doc/gcc-4.7/README.Bugs --enable-languages=c,c++,go,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.7 --enable-shared --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.7 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --enable-plugin --enable-objc-gc --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 4.7.2 (Ubuntu/Linaro 4.7.2-2ubuntu1)

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