SagittariusA
SagittariusA

Reputation: 5427

Error compiling with <list> C++

I don't know why it doesn't compile of I erase the comment in line

/*******************************/
waitThread.push_front(workerID);
/******************************/

Only if I leave the comment, it compiles...otherwise, I get a long exception ending with "declared here"...

/usr/include/c++/4.6/thread:126:5: error: declared here

maybe there is some problem with the definition of ... Can you explain me?

/*  g++ -std=c++0x -o manyThreads manyThreads.cpp -pthread */


#include <thread>
#include <iostream>
#include <mutex>
#include <time.h>
#include <list>


std::list<std::thread::id> myList;
std::mutex mutex;
std::list<std::thread> waitThread;

void insertList(std::thread::id identifier) {

mutex.lock();
myList.push_front(identifier);
mutex.unlock();

}

int main() {



std::list<std::thread::id>::iterator id;

std::list<std::thread>::iterator threadsIter;

int counter;


for(counter=0; counter<6; counter++) {

    std::thread workerID(insertList, workerID.get_id());

            /*******************************/
    waitThread.push_front(workerID);
            /******************************/
}


for(threadsIter=waitThread.begin(); threadsIter !=waitThread.end();threadsIter++)    {
    threadsIter->join();
}


for(id=myList.begin(); id != myList.end(); id++) {
    std::cout << *id << "\n";
}

return 0;
}

Upvotes: 1

Views: 131

Answers (3)

juanchopanza
juanchopanza

Reputation: 227370

std::thread is not copyable so you would have to move it in:

waitThread.push_front(std::move(workerID));

alternatively, you can move it by passing a temporary:

waitThread.push_front(std::thread(insertList, workerID.get_id());

Upvotes: 2

jcoder
jcoder

Reputation: 30035

std::thread is not copyable so you can't call push_front with it. It makes no sense to copy a thread, what would it do?

You can perhaps move the thread onto the list using

waitThread.push_front(std::move(workerID));

which will of course invalidate the thread object after that line.

However this line looks strange too :-

std::thread workerID(insertList, workerID.get_id());

I doubt it's valid to call get_id on an object that isn't constructed at that point.

Upvotes: 4

KBart
KBart

Reputation: 1598

It's not a comment, but a valid and (probably) essential statement in your program:

/*******************************/ -- comment
waitThread.push_front(workerID); -- statement
/******************************/ --comment

Upvotes: 1

Related Questions