首页 > 解决方案 > C++ USB 通信延迟

问题描述

ftd3xx.dll用来与设备通信

数据读取部分和数据写入部分分线程使用。

#include <thread>
#include <queue>
#include <array>
#include <windows.h>

using namespace std;

bool dataRead = false;
CRITICAL_SECTION sec;
queue< vector<unsigned short>> BufferQueue;

unsigned  WINAPI Write(void* arg) {

    int Width = 1000;

    vector<unsigned short> data;
    data.reserve(Width);

    while (Opened)
    {
        while (dataRead)
        {
            if (BufferQueue.size() > 0) {
                EnterCriticalSection(&sec); 
                data = BufferQueue.front();
                BufferQueue.pop();
                LeaveCriticalSection(&sec); 
            }
            else
            {
                this_thread::sleep_for(2ms);
                continue;
            }

            //wrtie something
        }

        if (!dataRead)
            break;
    }

    _endthreadex(0);
    return 0;
}


unsigned WINAPI Read(void* arg) {

    int Width = 1000;

    vector<unsigned short> data(Width);

    BYTE* acReadBuf = new BYTE[Width];
    ULONG ulBytesRead = 0;

    int idx = 0;

    Sleep(100);

    while (dataRead)
    {
        ftStatus = FT_ReadPipe(ftHandle, CstReadPipeNo, acReadBuf, Width, &ulBytesRead, NULL);

        if (FT_SUCCESS(ftStatus))
        {

            idx = 0;
            for (int i = 0; i < Width; i++) {
                data[i] = ((unsigned short)((unsigned short)acReadBuf[idx] | ((unsigned short)acReadBuf[idx + 1] << 8)));
                idx += 2;
            }

            EnterCriticalSection(&sec);
            if (BufferQueue.size() > 10000) {
                queue< vector<unsigned short>> empty;
                swap(BufferQueue, empty);

            }
            BufferQueue.push(data);
            LeaveCriticalSection(&sec);

        }
        else
        {
        }
    }

    _endthreadex(0);
    return 0;
}

void main() {

    //start
    InitializeCriticalSection(&sec); 

    dataRead = true;

    HANDLE r_hThread = NULL;
    unsigned  r_threadID;
    r_hThread = (HANDLE)_beginthreadex(NULL, 0, Read, NULL, 0, &r_threadID);


    HANDLE w_hThread = NULL;
    unsigned  w_threadID;
    w_hThread = (HANDLE)_beginthreadex(NULL, 0, Write, NULL, 0, &w_threadID);

    //....///

    //stop
    dataRead = false;;

    WaitForSingleObject(r_hThread, INFINITE);
    WaitForSingleObject(w_hThread, INFINITE);
    DeleteCriticalSection(&sec); 

}

我想直接对数组进行排队,但首先我将它用作向量。

重要的是,在运行其他程序甚至运行计算器时会发生数据丢失。

即使设备迟到或快地提供数据也是如此。

如果有人可以帮助我,我将不胜感激。

标签: c++usb

解决方案


推荐阅读