在 C++ 中使用 pthread

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2679885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:20:00  来源:igfitidea点击:

Using pthread in c++

c++linkerpthreadslinker-errors

提问by ogzylz

I am using pthread.hin a *.ccfile. when I try to use pthread_exit(0);or pthread_join(mythrds[yy],NULL);it says:

pthread.h在一个*.cc文件中使用。当我尝试使用pthread_exit(0);pthread_join(mythrds[yy],NULL);它说:

.cc:(.text+0x3e): undefined reference to `pthread_exit'

when complied very similar code in a *.cfile with gcc it work perfect. How Can I use pthread's in c++.. (I also added -lpthread)

*.c使用 gcc在文件中编译非常相似的代码时,它工作得很好。我如何在 c++ 中使用 pthread 的..(我还添加了 -lpthread)

..
void *myThreads ( void *ptr )
{
...
pthread_exit(0); 
}
..

flags:

标志:

g++ -lpthread -Wall -static -W -O9 -funroll-all-loops -finline -ffast-math

回答by WhirlWind

You might try using the -pthread option to g++.

您可以尝试对 g++ 使用 -pthread 选项。

   -pthread
       Adds support for multithreading with the pthreads library.  This
       option sets flags for both the preprocessor and linker.

回答by paxdiablo

Do your pthread header files have extern "C" { ... }around the function prototypes? That's the usual case for the linker not being able to link in C++.

您的 pthread 头文件是否extern "C" { ... }包含函数原型?这是链接器无法在 C++ 中链接的常见情况。

It occurs because C++ generally does name-mangling so that it can encode parameter details into symbols (allowing polymorphism). For example, the functions:

它发生是因为 C++ 通常会进行名称修改,以便它可以将参数详细信息编码为符号(允许多态)。例如,函数:

void x(int);
void x(void);
void x(char,int,float,double);

all get different linker symbols.

都得到不同的链接器符号。

If the header files don'thave the extern "C" { ... }, you may need to do it yourself:

如果头文件具备extern "C" { ... },可能需要自己做:

extern "C" {
    #include <pthread.h>
}

Hopefully that will work.

希望这会奏效。