c++ - 如何在 C++ 中正确管理发送到线程的消息
问题描述
在我的 Android 应用程序中,我使用 C++ 来完成一些工作。在我的 C++ 代码中,我使用线程来完成一些任务。使用这个例子和这个例子,我是这样进行的(我简化了实际代码以使其易于阅读):
std::thread* threadLocal;
std::queue<ThreadMessage*> queueLocale;
std::mutex mutexLocal;
std::condition_variable cvLocal;
struct ThreadMessage
{
ThreadMessage(int i)
{
id = i;
}
int id;
};
void MyWorkerThread::createThread()
{
if (!threadLocal)
{
threadLocal = new std::thread(&MyWorkerThread::process, this);
}
}
void MyWorkerThread::sendTask1()
{
if (threadLocal)
{
// message:
ThreadMessage* threadMessage = new ThreadMessage(MSG_TASK_1);
// send the message:
std::unique_lock<std::mutex> lock(mutexLocal);
queueLocale.push(std::move(threadMessage));
cvLocal.notify_one();
}
}
void MyWorkerThread::sendTask2()
{
if (threadLocal)
{
// message:
ThreadMessage* threadMessage = new ThreadMessage(MSG_TASK_2);
// send the message:
std::unique_lock<std::mutex> lock(mutexLocal);
queueLocale.push(std::move(threadMessage));
cvLocal.notify_one();
}
}
void MyWorkerThread::process()
{
while (1)
{
// init :
ThreadMessage* threadMessage = 0;
// waiting for messages :
{
std::unique_lock<std::mutex> lock(mutexLocal);
while (queueLocale.empty())
{
cvLocal.wait(lock);
}
threadMessage = std::move(queueLocale.front());
queueLocale.pop();
}
// tasks :
switch (threadMessage->id)
{
case MSG_TASK_1:
{
doSomeWork1();
delete threadMessage;
break;
}
case MSG_TASK_2:
{
doSomeWork2();
delete threadMessage;
break;
}
default:
{
delete threadMessage;
break;
}
}
}
}
它在大多数情况下运行良好,但有时,我的应用程序在delete threadMessage
调用 a 时崩溃,我不明白为什么(因为我看不到如何在同一个对象上调用它两次)。
以下是我需要向线程发送消息的原因,而不是每次我想运行时都创建新线程doSomeWork1()
或doSomeWork2()
:
- 和函数必须在同一个线程中
doSomeWork1()
执行doSomeWork2()
- 其中一个函数被非常频繁地调用(大约 200 次/秒),所以我不想每次都创建一个线程
所以我的问题是:向线程发送消息并在线程内部管理它以避免错误的正确方法是什么delete
?
谢谢你的帮助。
解决方案
推荐阅读
- node.js - 将变量传递给 bitbucket nodejs 脚本
- amazon-web-services - 注册容器实例 0 AWS ECS
- vue.js - NuxtJS 和 Tailwind 用户界面
- ios - SceneKit,如何正确支持背面几何图形的不透明度(或透明度)贴图?
- python - Django/Djagno REST 字段查找“范围”不返回范围,而是返回单值结果
- java - 开发android OCR(tesseract)时相机视图上的黑屏
- css - React & SCSS: SassError: 未定义的变量
- javascript - 如何反转“String.fromCodePoint”,即将字符串转换为代码点数组?
- sql-server - 错误:找不到“”的存储库。看起来这个实体没有在当前的“默认”连接中注册?
- php - Laravel8 phpunit 测试中没有生成代码覆盖率报告html?