首页 > 解决方案 > 如何在 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()

所以我的问题是:向线程发送消息并在线程内部管理它以避免错误的正确方法是什么delete

谢谢你的帮助。

标签: c++multithreading

解决方案


推荐阅读