いちばん失敗した人決定戦

C++で処理を止めずにすべてのスレッドを起動したいのですがうまくいきません。
スレッドをvoid AddThread(const std::thread& th)のように受け取りvectorに格納することはできないのでしょうか。

static std::vector<const std::thread*> ths;
void AddThread(const std::thread& th) {
ths.push_back(&th);
}

void ThreadFunc1() {
while (true) {
std::cout << "ThreadFunc1" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}


void SartThreadFunc1() {
// AddThreadを使わずに ths.push_back(std::thread(ThreadFunc1));のようにすればうまくいった
AddThread(std::thread(ThreadFunc1));
}

int main() {
for (int i = 0; i < 2; i++) {
SartThreadFunc1();
}

for (const std::thread* th: ths) {
// constなのでjoin()を呼び出せない!!
th->join();
}

return 0;
}

A 回答 (2件)

ほそく.



コメントに
// AddThreadを使わずに ths.push_back(std::thread(ThreadFunc1));のようにすればうまくいった
ってあるけど, そこを変えるだけだと
static std::vector<const std::thread*> ths;
と型があわないよ.
    • good
    • 0

「constなのでjoin()を呼び出せない!!」が原因なのだとしたら


const にしない
しか方法はないのではないかな.
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!