简体   繁体   English

如何在主函数和线程之间传输数据?

[英]How to transfer data between main function and threads?

I want to store the threads that I have created in my main function in an array and later access them in my Thread class.我想将我在主函数中创建的线程存储在一个数组中,然后在我的 Thread 类中访问它们。 What would be the best way to do this?.什么是最好的方法来做到这一点? Below is the structure of my code.下面是我的代码结构。

Main.cpp:主.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我的类.cpp

MyClass::MyThread(....){
I want to access the array of threads here.
}

I have tried mutex and cv and add these threads into a queue but it is generating many errors.我尝试了互斥锁和 cv 并将这些线程添加到队列中,但它产生了许多错误。 What is the best way to solve this?解决这个问题的最佳方法是什么?

I am not 100% sure if array fits the bill - do you know how many threads there will be?我不是 100% 确定数组是否符合要求 - 你知道会有多少线程吗?

Maybe a vector is better:也许向量更好:

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);
}

Now you have all your threads neatly in a vector (note I did not test this with you code because there is not enough of it to test... its not a complete example)现在你把所有的线程都整齐地放在一个向量中(注意我没有用你的代码测试这个,因为没有足够的代码来测试......它不是一个完整的例子)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM