线程完成后在另一线程中调用方法
Calling a method in another thread after a thread is finished
我正在尝试平行我的程序,但是由于我对线程非常新,所以我面临一些问题。
我有两种方法是同一类的一部分。其中一种方法可以在循环中进行一些计算,并在向量中推出结果,其他方法(Runtheresult(采用矢量并使用获得的向量启动线程。我希望启动另一个线程以运行下一个获得的结果,每次runtheresult完成结果,同时将最大线程数限制为4。
。我程序的结构就像:
void runTheResult(vector<double>& u){
//process 'u' and launch a thread
};
void method(){
for(...){
//calculate
for(...){
//put the calculations in vector<double>result
};
runTheResult(result);
};
};
我已经大量搜索了这一点,其中一种解决方案是维护消息que。但是,这个问题是,如果我实现了一个Que,我必须在一段时间内定期与另一个线程检查该Que。如果我在while(true){//check for new messages if number of threads is less than five}
这样的循环时使用时,我会损失很多处理能力,如果我选择将循环放入条件时,我会浪费处理能力。我在线程中运行的功能每个需要2-5秒,我要处理约1k至50k的功能,因此即使每循环的延迟的一秒钟也很多。
每次完成RunthereSult时,是否可以运行Runtheresultin另一个线程?还是有更好的方法?
其他人告诉您使用消息队列,因为这是最安全的方法。您的程序必须至少具有用户(您或最终用户(可以与之交互的主线程。只要您的程序运行,此主线程就会循环。您在此处进行消息处理
// this is not actually running the result now
// this only sends it to the main thread that will run the result
void runTheResult(vector<double>& u){
//process 'u' and launch a thread.
// @NOTE Launching a thread again will not be beneficial as it will still be blocked
// by the mutex
// convert/store vector into Message. To make it usable for other types
// or you can just change Message to double
Message u_message = to_message(u)
std::lock_guard<std::mutex> lock(message_mutex);
messages_shared.append(u_message);
};
void method() // runs on worker thread
{
for(...){
//put the calculations in vector<double>result
};
runTheResult(result);
}
void getMessages_safe(std::vector<Messages>& outMessages_safe)
{
// as Ted Lyngo suggests, using lock_guard is best practice. See edit for alternative
std::lock_guard<std::mutex> lock(message_mutex);
outMessages_safe = messages_shared;
messages_shared.clear();
}
std::vector<Message> messages_shared;
std::mutex message_mutex;
void main() { // this runs on the very first thread of the program
while (isProgramRunning)
{
std::vector<Message> messages_safe; // safe to access by this thread only
getMessages_safe(messages_safe);
// dispatch messages to whoever needs it
// launch worker thread
}
}
相关文章:
- 如何声明由多个线程调用的 C++ DLL 的内部类,而无需导出类
- 非静态成员失败的线程调用函数
- 线程调用的函数对对象删除是否安全?
- 将类成员函数作为线程调用到另一个类成员函数时发出警告消息
- 通过 Qt 中的线程调用 Rust 库
- Qt信号和插槽如果从QRunnable或其他线程调用,则不起作用
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 由并发无序映射查找线程调用的函数是否安全?
- 如何从另一个线程调用颤振引擎方法
- C++ std::线程调用方法,从对象原因到调用此类的析构函数
- 从多个线程调用 std::shuffle
- std::thread::join() 可以从非父线程调用吗?
- 如何使用 Win32 API 从 Excel VBA 中的非"Single-Threaded Apartment"线程调用 InternetGetProxyInfo
- 带参数的线程调用库函数
- 如何在本机C++中跨线程调用(在主线程上回调)
- 如果两个线程调用同一个函数,但函数中的所有变量都是局部变量,我还需要担心线程之间共享数据吗?
- 优雅断言函数不是从多个线程调用的
- 从第二个线程调用Qt信号有效 - >对连接的插槽没有影响
- 包装标准::线程调用函数
- 从 Visual C++ 2010 中的单独线程调用消息框