线程数组

时间:2014-10-14 16:25:04

标签: c++ multithreading c++11

我正在尝试创建一个线程数组,并为每个线程提供一个函数但不能正常工作

Reader *readers = new Reader[10];

thread *ts = new thread[10];

for (int i = 0; i<10; i++){
    readers[i].setAll(q, "t" + i);
    ts[i] = thread(readers[i].run); //Error: "cannot be referenced. its a deleted function"
}

运行功能:

void Reader::run(){
    log(this->source);
    log.log("starting");

    while (flag){
        this->m = this->q.get(this->source);
        log.log("retrieved " + m.toString());
        if (m.getData().compare("stop") && m.getTarget().compare(this->source))
        {
            log.log("stopping");
            this->setFlag(false);//stop the current thread if the message is "stop"
        }
        else{
            if (!m.getTarget().compare(source)){//if the message isnt from the current thread then put the message back
                string dest = m.getSource();
                m.setSource(this->source);
                log.log("putting back [" + dest + "->" + m.getTarget() + ":" + " " + m.getData() + "] as " + m.toString());
                q.put(m);
                log.log("done putting back " + m.toString());
            }
        }
    }
}

我实际上是在尝试执行以下代码:

thread t0(readers[0].run);
thread t1(readers[1].run);
etc...

但它也给了我同样的错误:

The error message

2 个答案:

答案 0 :(得分:1)

如果你正在使用c ++ 11,你可能想利用漂亮的内存管理和绑定功能:

(编辑:更新代码以回应评论)

#include <iostream>
#include <thread>
#include <memory>
#include <vector>

using namespace std;

struct runner
{
    void run() {
        cout << "hello" << endl;
    }
};

int main()
{
    vector<unique_ptr<runner>> runners;
    for(size_t i = 0 ; i < 10 ; ++i) {
        runners.emplace_back(new runner);
    }

    vector<thread> threads;
    for(const auto& r : runners) {
        threads.emplace_back(&runner::run, r.get());
    }

    for(auto& t : threads) {
        t.join();
    }

   return 0;
}

答案 1 :(得分:0)

虽然readers[i].run看起来应该将一个对象绑定到一个成员函数来生成一个可调用对象,但遗憾的是它并没有。相反,您需要将指向成员函数的指针和指针(或引用包装器)作为单独的参数传递给对象:

thread(&Reader::run, &readers[i]);    // or std::ref(readers[i])

或者您可能会发现将函数调用包装在lambda中更好:

thread([=]{readers[i].run();})