C++ 如何在主函数和线程之间传输数据?
我想将我在主函数中创建的线程存储在一个数组中,然后在我的线程类中访问它们。最好的方法是什么?。下面是我的代码结构 Main.cpp:C++ 如何在主函数和线程之间传输数据?,c++,c++11,C++,C++11,我想将我在主函数中创建的线程存储在一个数组中,然后在我的线程类中访问它们。最好的方法是什么?。下面是我的代码结构 Main.cpp: int main(){ //do something while ((new_socket = socket.Accept())) { std::thread mythread(&Myclass::MyThread, &myclass, std::move(new_socket), para1);
int main(){
//do something
while ((new_socket = socket.Accept())) {
std::thread mythread(&Myclass::MyThread, &myclass,
std::move(new_socket), para1);
// I want to store the above threads created in an array which can later be accessed in a different thread class
}
}
MyClass.cpp
MyClass::MyThread(....){
I want to access the array of threads here.
}
我尝试了互斥和cv,并将这些线程添加到队列中,但它产生了许多错误。解决这个问题的最佳方法是什么?我不能100%确定数组是否符合要求-您知道将有多少线程吗 也许向量更好:
std::vector<std::thread> threads; // could be a member - used to store the threads
while ((new_socket = socket.Accept()))
{
// Construct the thread in place inside the vector
threads.emplace_back(&Myclass::MyThread, &myclass, std::move(new_socket), para1);
}
现在你把所有的线程整齐地放在一个向量中,我没有用你的代码测试它,因为没有足够的线程来测试。。。这不是一个完整的示例您知道如何在数组中存储对象吗?现在只需对线程对象执行相同的操作。