在构建时处理 pthread 宏错误?

Handeling pthread Macro Error at Build Time?

提问人:Gil 提问时间:11/11/2023 更新时间:11/11/2023 访问量:24

问:

我已经在很长一段时间内遇到同样的错误了。下面的 C++ 示例被简化,因为我第一次遇到此错误是在构建新下载的库时。我不知道如何处理这个问题。我已经重新下载了 g++、gcc、essential build 和 libc6。

下面是一个基本的 C++ 代码来演示错误:

#include <iostream>
#include <pthread.h>

int main() {
    pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;

    pthread_mutex_destroy(&m);

    std::cout << "Hello, World!" << std::endl;
    return 0;
}

以下是CMakeLists.txt文件:

project(clion_pthread)

set(CMAKE_CXX_STANDARD 14)

# Find the Threads package (this finds pthreads on UNIX)
find_package(Threads REQUIRED)

# Add your executable
add_executable(clion_pthread main.cpp)

# Link the executable to the Threads library
target_link_libraries(clion_pthread Threads::Threads)

错误

clion_pthread/cmake-build-debug --target clion_pthread -- -j 6
[ 50%] Building CXX object CMakeFiles/clion_pthread.dir/main.cpp.o
In file included from /usr/include/x86_64-linux-gnu/c++/9/bits/gthr-default.h:35,
                 from /usr/include/x86_64-linux-gnu/c++/9/bits/gthr.h:148,
                 from /usr/include/c++/9/ext/atomicity.h:35,
                 from /usr/include/c++/9/bits/ios_base.h:39,
                 from /usr/include/c++/9/ios:42,
                 from /usr/include/c++/9/ostream:38,
                 from /usr/include/c++/9/iostream:39,
                 from /clion_pthread/main.cpp:1:
clion_pthread/main.cpp: In function ‘int main()’:
clion_pthread/main.cpp:5:25: error: ‘__PTHREAD_SPINS’ was not declared in this scope
    5 |     pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
      |                         ^~~~~~~~~~~~~~~~~~~~~~~~~
make[3]: *** [CMakeFiles/clion_pthread.dir/build.make:76: CMakeFiles/clion_pthread.dir/main.cpp.o] Error 1
make[2]: *** [CMakeFiles/Makefile2:83: CMakeFiles/clion_pthread.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:90: CMakeFiles/clion_pthread.dir/rule] Error 2
make: *** [Makefile:124: clion_pthread] Error 2

操作系统

No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.6 LTS
Release:    20.04
Codename:   focal

C++ Ubuntu clion cmakelists-options

评论

0赞 Ted Lyngmo 11/11/2023
我也有点困惑,因为看起来你做对了,但是,为什么要在 C++ 中使用?你知道你有 C++ 管理线程的方法,对吧?pthread
0赞 Gil 11/11/2023
最初我试图构建一些从 git 下载的库:github.com/microsoft/SEAL。在构建时,我收到与上面提供的错误类似的错误。这就是为什么我决定用一个小例子进行测试。
2赞 Pepijn Kramer 11/11/2023
你甚至确定PTHREAD_MUTEX_INITIALIZER是你需要摧毁的东西吗?可以是静态/全局的。但是@TedLyngmo在编写新的C++代码时是正确的,您应该使用 std::thread(或C++20 的 std::jthread)和 std::mutex/std::scoped_lock
0赞 Red.Wave 11/11/2023
你也试过vcpkg吗?它必须比手动配置更容易。 依赖在 Windows 平台上很奇怪,因为 Windows 不是 POSIX 操作系统;与许多其他 API 一样,它有其独特的线程 API。除非你是在 mingw 或 cygwin 上构建的,否则你不应该在你的代码库中看到。pthreadpthread

答: 暂无答案