如何解决如何在主函数和线程之间传输数据?
我想将在主函数中创建的线程存储在数组中,然后在Thread类中访问它们。最好的方法是什么?下面是我的代码的结构。
Main.cpp:
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);
}
现在您可以将所有线程整齐地放在一个向量中(请注意,我没有用您的代码对其进行测试,因为没有足够的代码可以对其进行测试……这不是一个完整的示例)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。