iNukeLaPeste
iNukeLaPeste

Reputation: 89

Vector of threads in C++

I am trying to use a vector of threads. I will receive an int as a parameter, which will be the number of threads I will have to create.

I tried something like this:

#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);
}

But I get this compilation error:

/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

by compiling using the following command:

g++ -W -Wall -Werror -Wextra threads.cpp

What's wrong here?

Upvotes: 1

Views: 2394

Answers (1)

Breealzibub
Breealzibub

Reputation: 8095

The std::thread class utilizes pthreads in Linux, so you need to add the -pthread compiler flag to your command;

g++ -W -Wall -Werror -Wextra -pthread threads.cpp

Upvotes: 5

Related Questions