代码如下
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;
};
单看你这段代码,即使你不用lock也不会有冲突,因为你的线程会等待setevent后才会继续,所以问题不在这部分,你需要明确你的问题。