TCP文件傳輸-二級流水線高效模式具體代碼實現 mutex 條件變量condition_variable futrue運用

相比與上一篇那種線程同步方式,上篇利用async的生命週期作爲同步點。而實際情況中 子線程不會一直退出和不斷的開啓,我門需要人爲的控制線程同步且退出.
這裏我門採用隊列的方式,主線程接收完數據往隊列裏面投遞,通知子線程,子線程負責取數據 子線程數據處理結束後會繼續通知主線程,主線層繼續投遞。 最後利用futrue控制程序的退出.

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------

// tcp file transport Server

//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------


#include <Winsock2.h>
#include <iostream>
#include <thread>
#include<fstream>
#pragma comment(lib, "Ws2_32.lib")

using namespace std;

/*協議頭*/
class FileHeader
{
public:
    void Setname(wchar_t* szfillname)
    {
        wcscpy(_szfillname, szfillname);
    }

    const wchar_t* Getname(void)const
    {
        return _szfillname;
    }

    void Setsize(unsigned long long ullsize)
    {
        _ullfilesize = ullsize;
    }
    unsigned long long Getsize(void)
    {
        return _ullfilesize;
    }

private:
    wchar_t _szfillname[200];//用於裝名字
    unsigned long long _ullfilesize;//用於裝文件大小的
};

int wmain(int ac,wchar_t* av[])
{
    /* 初始化winsock2庫 */
    //Step 0. Initialize winsock2 library...
    WSADATA wsaData;
    wcout << av[1] << endl;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
    {
        return 1;
    }

    // Step 1. Ask system for a socket.this socket is waiter
    SOCKET sockServer = ::socket(PF_INET, SOCK_STREAM, 0);

    if (sockServer == INVALID_SOCKET)
    {
        return 1;
    }

    //Step 2. bind the socket to a local address and port.接待套接字
    sockaddr_in addrServer = { 0 };
    addrServer.sin_family = AF_INET;
    addrServer.sin_addr.S_un.S_addr = inet_addr("88.88.106.34");
    //host to network short.小端轉大端
    addrServer.sin_port = htons(30001);


    if (::bind(sockServer, reinterpret_cast<const sockaddr*>(&addrServer),
        sizeof addrServer) == SOCKET_ERROR)
    {
        return 1;
    }

    // Step 3. listen. 監聽隊列的設置  監聽五個套接字的連接
    if (listen(sockServer, 5) == SOCKET_ERROR)
    {
        return 1;
    }

    // Step 4. accept.
    sockaddr_in addrClient = { 0 }; //將對放的信息保存在這個結構體裏
    int iLength = sizeof addrClient;
    SOCKET sockClient = INVALID_SOCKET;

    while (true)
    {
        //該返回的套接字纔是用於收發的套接字-這裏的邏輯是 一個連接開一個線程
        sockClient = ::accept(sockServer, reinterpret_cast<sockaddr*>(&addrClient), &iLength);
        if (sockClient == INVALID_SOCKET)
        {
            return 1;
        }
        
        thread t1([sockClient,av]()->void {

            //open  a file and retrieve the information.
            fstream fs;
            fs.open(av[1], fstream::in|fstream::binary);
            if (!fs)
            {
                return;
            }
            wcout << av[1] << endl;
            unsigned long long ullSize = 0ull;
            fs.seekg(0, fstream::end); //文件指針移到末尾
            ullSize = fs.tellg();      //獲取文件的大小
            fs.seekg(0, fstream::beg); //再將文件指針移到起始位置
    
            //send file header
            FileHeader header;
            header.Setsize(ullSize);
            header.Setname(av[1]);
            unsigned long long iResult = ::send(sockClient, reinterpret_cast<const char*>(&header), sizeof(header), 0);
            if (iResult<=0)
            {
                return;
            }

            //send body of file 多次發送
            char  readingBuf[4096];
            while(!fs.eof())
            {
                fs.read(readingBuf, 4096);              //讀進buf
                iResult = fs.gcount() ;                  //這裏需要注意的是tellg()函數是累計的 上次實際讀了多少應該用gcount()函數
                ::send(sockClient, reinterpret_cast<const char*>(readingBuf), iResult, 0);
                //cout << "shijisend:" << shijie<<"tellg:" << iResult<<"last"<< lastReadSize <<endl;
            }
            fs.close();    
            closesocket(sockClient);
        });

        t1.detach();
    }

    closesocket(sockServer);
    WSACleanup();
    return 0;
}

//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

// tcp file transport Client

//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

#include <Winsock2.h>
// Need to link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
#include <iostream>
#include "future"

#include <fstream>
#include "thread"
#include<future>
#include<queue>
#include<condition_variable>  //條件變量

#define  BUFFSIZE 1024*1024*50
using namespace std;

class Header
{
public:
    void Setname(wchar_t* szfillname)
    {
        wcscpy(_szfillname, szfillname);
    }

    const wchar_t* Getname(void)const
    {
        return _szfillname;
    }

    void Setsize(unsigned long long ullsize)
    {
        _ullfilesize = ullsize;
    }
    unsigned long long Getsize(void)
    {
        return _ullfilesize;
    }

private:
    wchar_t _szfillname[200];//用於裝名字
    unsigned long long _ullfilesize;//用於裝文件大小的
};

 

typedef  struct _Entity
{
    bool bExit;   //判斷是否是最後一接收
    char*currentBuf;//切換緩衝區的指針
    int  iSize;        //當前緩衝區裏面實際數據的大小
}Entity,*PEntity;
 
//定義全局隊列
queue<Entity>taskQueue;
mutex mx;  //這裏用於和主線程互斥
condition_variable cv; //cv.wait()阻塞 cv.notify()甦醒 類似於windows信號
mutex mxCv;  //該鎖用於條件變量

future<int>fut; //用於子線程和主線程退出同步
int wmain(int ac, wchar_t* av[])
{
    /* 初始化winsock2庫 */
    // Step 0. Initialize winsock2 library...
    WSADATA wsaData;

    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
    {
        return 1;
    }

    //1.創建套接字
    SOCKET socksever = ::socket(PF_INET, SOCK_STREAM, 0);
    if (socksever == INVALID_SOCKET)
    {
        return 1;
    }
    //2.connect
    sockaddr_in addrsocksever = { 0 };
    addrsocksever.sin_family = AF_INET;
    addrsocksever.sin_addr.S_un.S_addr = inet_addr("192.168.0.44");
    addrsocksever.sin_port = htons(30001);

    if (::connect(socksever, reinterpret_cast<const sockaddr*>
        (&addrsocksever), sizeof addrsocksever) == SOCKET_ERROR)
    {
        return 1;
    }
    //3.receive header of file 
    Header fileheader;
    int ineedtorecieve = sizeof fileheader;
    int irecv = 0; //實際接多少
    int itotalrecv = 0;
    do
    {
        irecv = ::recv(socksever, reinterpret_cast<char*>(&fileheader) + itotalrecv, ineedtorecieve, 0);
        itotalrecv += irecv;
    } while ((ineedtorecieve -= irecv) > 0);

    // create sub thread 子線程乾的事 從對列取出數據進行IO操作
    promise<int>prom; //用於控制子主線程同步退出
    fut = prom.get_future();
    thread t1([av,&prom](void)->void {

        fstream fs;
        fs.open(av[1], iostream::out | iostream::binary | iostream::trunc);
        if (!fs)
        {
            return ;
        }
        while (true)
        {

            //第一個進來的線程拿到鎖後,其他線程就會阻塞 這裏用於和主線程互斥
            unique_lock<mutex>interLock(mx);
            if (taskQueue.size > 0)
            {
                if (taskQueue.front().bExit)
                {
                    //退出
                    fs.close();
                    prom.set_value(1);
                    return;
                }
                //寫文件
                fs.write(taskQueue.front().currentBuf, taskQueue.front().iSize);
                taskQueue.pop();
            }

            interLock.unlock();
            unique_lock<mutex>lock(mxCv); //不會卡在這裏 會卡在下面
            cv.wait(lock);  //目的防止程序一直while循環暫用資源 阻塞在這裏等條件變量notify()也就是主線程push到隊列裏面的時候甦醒 
        }

        return;
    });

    t1.detach();  //脫離主線程聯繫

    //主線程乾的事,接收數據,將數據存入緩衝區 投入隊列,切換緩衝區 通知子線程不用cv.wait()了
    char*bufa = new char[BUFFSIZE];
    char*bufb = new char[BUFFSIZE];
    char* nextbuf = bufa;            //指針剛開始執行bufa

    unsigned long long ullremindersize = fileheader.Getsize();
    while (ullremindersize > 0)
    {
        itotalrecv = 0;//這個地方很重要,每緩衝區塞滿了後,這個必須清零

        ineedtorecieve = BUFFSIZE > ullremindersize ? ullremindersize : BUFFSIZE;

        while (ineedtorecieve > 0)
        {

            irecv = ::recv(socksever, nextbuf + itotalrecv, ineedtorecieve, 0);
            ullremindersize -= irecv;
            itotalrecv += irecv;
            ineedtorecieve -= irecv;
        }

        //用於和子線程同步 子線程通知主線程我已經寫完了,你該push了
        unique_lock<mutex>interLock(mx);
        if (itotalrecv > 0)
        {
            //投遞隊列
            Entity entity;
            entity.bExit = false;
            entity.currentBuf = nextbuf;
            entity.iSize = itotalrecv;
            taskQueue.push(entity);
            interLock.unlock();//釋放鎖,讓子線程繼續
            cv.notify_all();
            nextbuf = nextbuf == bufa ? bufb : bufa;
        }

    }

    //最後一次接收數據,主線程如果執行的很快的話先退出while要保證子線程先退出
    unique_lock<mutex>interLock(mx);
    Entity entity;
    entity.bExit = true;
    entity.currentBuf = nullptr;
    entity.iSize = 0;
    taskQueue.push(entity);
    cv.notify_all();
    
    fut.get();//主線程阻塞在這裏 直到子線程prom.setvalue()

    closesocket(socksever);

    if (bufa)
    {
        delete[]bufa;
        bufa = nullptr;
    }
    if (bufb)
    {
        delete[]bufb;
        bufb = nullptr;
    }
    return 0;

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章