为什么使用了EnterCriticalSection之后指针字符串添加字符还会引发访问冲突?

代码如下

MemLock Locker;
LPSTR hComWriteBuffer;
DWORD dwComBytesToWrite;
HANDLE    hComSendEvent;
void main()
{
  hComSendEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
  hComWriteBuffer = "G90";
  (HANDLE)::_beginthreadex(nullptr, 0, ThreadComWrite, nullptr, 0, nullptr);
  Locker.lock();
  *(hComWriteBuffer + 4) = '\n';
  *(hComWriteBuffer + 5) = '\0';
  Locker.unlock();
  dwComBytesToWrite = strlen(hComWriteBuffer);
  SetEvent(hComSendEvent);
}

//串口写线程
unsigned int __stdcall  ThreadComWrite(void* pv)
{
  ...
  WaitForSingleObject(hComSendEvent, INFINITE))
  WriteFile(hCom, hComWriteBuffer, dwComBytesToWrite, NULL, &oEvt);\
  ...
}

class MemLock
{
public:
    MemLock()
    {
        ::InitializeCriticalSection(&locker);
    }
    ~MemLock()
    {
        ::DeleteCriticalSection(&locker);
    }

    void lock()
    {
        ::EnterCriticalSection(&locker);
        Busy = 1;
    }

    void unlock()
    {
        ::LeaveCriticalSection(&locker);
        Busy = 0;
    }

    bool try_lock()
    {
        return !!::TryEnterCriticalSection(&locker);
    }

    bool IsBusy()
    {
        return (bool)Busy;
    }

private:
    CRITICAL_SECTION    locker;
    WORD                Busy;
};



阅读 2.1k
1 个回答

单看你这段代码,即使你不用lock也不会有冲突,因为你的线程会等待setevent后才会继续,所以问题不在这部分,你需要明确你的问题。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏