c++ - C++ 中的线程 vector

标签 c++ multithreading vector

我正在尝试使用线程 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/

相关文章:

c++ - 为什么虚拟分配的行为与相同签名的其他虚拟功能不同?

c++ - 有没有一种干净的方法可以在 leonardo 中禁用 USBCore 的 RX 控制?

c# - 在 parallel.ForEach 循环中获取线程 ID

C++ vector.push_back() 使 m 程序崩溃

c++ - 在 C++ 中声明 vector 时出现意外错误

c++ - 取消引用空指针数组

java - 内存泄漏使用 JNI 将数组从 C++ 发送到 Java

java - 终止 Java 线程

python - Python 中的并行处理/线程

c++ - 查找预分配 vector C++ 的非空索引