做一个上位机软件,需要发送命令给设备,并同时不断接收设备返回的数据,但是发现不能再两个不同的线程中同时访问设备,否则会产生冲突,请问有什么解决办法吗

解决方案 »

  1.   

    做好线程同步,用Mutex等来防止同时访问
      

  2.   


    // 互斥量类
    // 关键数据,代码的保护
    #ifndef _MyMutex_H_
    #define _MyMutex_H_class MyMutex
    {
    private:
    HANDLE SynMutex;public:
    MyMutex();
    ~MyMutex();
    void Build(LPCTSTR mutexName); // 建立互斥器
    bool EnterSynCode(); // 进入同步代码区,无限等待
    bool EnterSynCode(DWORD WaitTime); // 进入同步代码区,有限等待
    bool LeaveSynCode(); // 离开关键代码区
    };#endif#include "stdafx.h"
    #include <windows.h>
    #include "xMutexET199.h"MyMutex::MyMutex()
    {
    SynMutex = NULL;
    }MyMutex::~MyMutex()
    {
    if (SynMutex != NULL)
    {
    CloseHandle(SynMutex);
    SynMutex = NULL;
    }
    }void MyMutex::Build(LPCTSTR mutexName)
    {
    if(SynMutex)
    {
    CloseHandle(SynMutex);
    SynMutex = NULL;
    }
    SynMutex = OpenMutex(SYNCHRONIZE, FALSE, mutexName);
    if (SynMutex == NULL)
    SynMutex = CreateMutex(NULL, FALSE, mutexName);
    }bool MyMutex::EnterSynCode()
    {
    DWORD const WaitState = WaitForSingleObject(SynMutex, INFINITE);
    return(true);
    }bool MyMutex::EnterSynCode(DWORD WaitTime)
    {
    DWORD const WaitState = WaitForSingleObject(SynMutex, WaitTime);
    if (WAIT_TIMEOUT==WaitState) return(false);
    return(true);
    }bool MyMutex::LeaveSynCode()
    {
    return(!!ReleaseMutex(SynMutex));
    }
      

  3.   

    使用临界区
    InitializeCriticalSection
    EnterCriticalSection
    LeaveCriticalSection
    DeleteCriticalSection