没有正确使用互斥锁?继续过去的问题

Mutex not correctly used? Continuation of past questions

本文关键字:继续 过去 问题      更新时间:2023-10-16

我有第二个问题,是这个线程的延续:Windows如何为线程选择内存?

void ThreadTest(LPTSTR* Pointer, mutex* MutexPtr)
{
    MutexPtr->lock();   
    wcout << *Pointer << endl;
    MutexPtr->unlock();
    return;
}
void FakeMain()
{
    mutex Mut;
    mutex* MutPtr = &Mut;
    LPTSTR Image = L"First String";
    LPTSTR* StrPointer = &Image;
    thread Test(ThreadTest, StrPointer, MutPtr);
    MutPtr->lock();
    if (true)
    {
        NewStringFunction(Image);
        MutPtr-unlock() // Added with the comment of Mike
        Test.join();        
        LPTSTR* StrPointer = &Image;        
        thread Test(ThreadTest, StrPointer, MutPtr);                
    }
    MutPtr->lock();
    Test.join();
    MutPtr->unlock();
    return;
};
void NewStringFunction(LPTSTR& Image)
{
    LPTSTR TempString = L"New String for new Thread";
    Image = TempString;
    return;
};

上面的代码是模拟我的代码,我有问题。流程应该如下所示:

  • FakeMain()初始化变量并设置String;
  • FakeMain然后为这个字符串创建一个线程来打印。新线程打印字符串。
  • 打印线程被销毁,新的字符串由单独的外部函数生成。
  • 创建一个新线程来打印这个新消息

我有一个"if"语句,因为实际代码中有一个线程正在if语句中,我想确保内存分配表示这一点。字符串在单独的函数中更改,因为这是实际代码的操作方式。我销毁了第一个线程,因为在实际代码中,线程正在显示一个改变大小的窗口,因此需要一个新线程。

从写这段代码,我觉得我的互斥锁没有正确实现。这段代码没有给出字符串错误,但我认为互斥锁正在被线程覆盖(我认为)。在程序运行时观察内存,第一个线程实例可能会重写互斥锁,我不确定。主线程中的最后一个mutex.lock()抛出错误。我是否正确地使用了互斥锁?是否有一个更干净的方式,我应该锁定/停止线程?

不要使用互斥锁,也不要共享内存。

暴力破解:

发送者需要做的就是

Message msg = new Message(<important information>);
// send msg

接收码

// use msg  
delete msg;

非常简单的编写和使用,但有内存泄漏:如果消息从未得到服务,它永远不会返回RAM。

更好的版本可能变得非常复杂。下面是一个简单的大纲:

Create a pool of Messages
Assign all messages to a FreeList
Create a mutex to protect FreeList

freellist是当前未被使用的消息列表。当需要发送消息时,第一个消息将从freellist中删除并传递给调用者。调用方用要发送的信息填写Message,然后发送Message。

接收者负责将消息返回给FreeList。

添加一些函数来管理freellist

GetMsg <changed to prevent collision with Windows GetMessage function>
    Message = NULL
    acquire mutex
    if FreeList not empty
        remove Message from FreeList
    release mutex
    return message            
ReturnMsg
    acquire mutex
    Add Message to FreeList
    release mutex

发送者有点复杂

Message msg = GetMessage()
If msg not NULL
    msg.set(<important information>);
    std::thread temp(ThreadTest, msg);
    temp.detatch
else
    // log and handle <- can be simple like abort or complicated like recover lost Messages

接收器仍然很简单

// use msg  
ReturnMessage(msg);

这对内存泄漏有一个上限,并且可以很容易地跟踪哪些消息从未返回(在池中,而不是在FreeList中),因此您可以尝试跟踪哪些作业被阻塞或爆炸。修复锁或放大是另一个问题。

OP有一个好主意,我认为我是对的。下面是一个基本线程函数的核心。它挂在后台运行,直到发送终止消息。它阻塞等待消息,消费消息,然后将其放回freellist并阻塞,直到另一个消息到达。

void threadfunc()
{
    MSG winmsg;
    BOOL rval;
    while (GetMessage(&winmsg, (HWND__ *) -1, 0, 0) != -1)
    {
        Message * msg = (Message *)winmsg.wParam;
        // do stuff with msg
        ReturnMsg(msg);
    }
    // GetMessage failed. Find out why and try to recover or die gracefully
}

需要像

这样的东西来支持
bool PostMsg(<Important Information>,
             DWORD & BackgroundThreadId)
{
    Message * msg = GetMsg();
    if (msg != NULL)
    {
         msg.set(<Important Information>)
        if (PostThreadMessage(BackgroundThreadId,
                              WM_USER,
                              (WPARAM) msg,
                              0); != 0)
        {
            return true;
        }
        else
        {
            // failed. Find out why and try to recover or die gracefully
            ReturnMsg(msg);
            return false;
        }
    }
    else
    {
        // out of free messages. Try to find out why
    }
}
PostMsg为后台线程的消息队列提供消息。消息来自自由列表,只有自由列表需要互斥保护。可以使用多个线程。我不认为这可以用std::thread来完成,因为std::thread不能访问底层线程句柄(只是检查了一下,可以这样做)或线程的消息队列。不管怎样,它都是基于Windows调用的,所以忘记可移植性吧。

if语句之前的锁调用没有匹配的解锁。此外,如果主线程在测试头之前获得互斥锁,则可能出现死锁。此外,您的最后一个连接正在等待错误的线程。据我所知,没有理由锁定互斥锁来执行连接。