我正在尝试使用线程 vector 。我将收到一个 int 作为参数,这将是我必须创建的线程数。
我试过这样的:
#include <iostream>
#include <thread>
#include <vector>
void credo()
{
std::cout << "threads" << std::endl;
}
void threads_creation()
{
int i;
std::vector<std::thread> threads_tab;
i = 0;
while(i < 2)
{
threads_tab.push_back(std::thread(credo));
i++;
}
}
int main()
{
threads_creation();
return (0);
}
但是我得到这个编译错误:
/tmp/ccouS4PY.o: In function `std::thread::thread<void (&)()>(void (&)())':
threads.cpp:(.text._ZNSt6threadC2IRFvvEJEEEOT_DpOT0_[_ZNSt6threadC5IRFvvEJEEEOT_DpOT0_]+0x21): undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
通过使用以下命令进行编译:
g++ -W -Wall -Werror -Wextra threads.cpp
这里有什么问题吗?
最佳答案
std::thread 类在 Linux 中使用 pthreads,因此您需要在命令中添加 -pthread
编译器标志;
g++ -W -Wall -Werror -Wextra -pthread threads.cpp
关于c++ - C++ 中的线程 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43706286/