📄 threadfunc.cpp
字号:
// ThreadFunc.cpp : implementation file
//
#include "stdafx.h"
#include "FileTransferServer.h"
#include "ThreadFunc.h"
#include <process.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// ThreadFunc
ThreadFunc::ThreadFunc()
{
}
ThreadFunc::~ThreadFunc()
{
}
// Do not edit the following lines, which are needed by ClassWizard.
#if 0
BEGIN_MESSAGE_MAP(ThreadFunc, CAsyncSocket)
//{{AFX_MSG_MAP(ThreadFunc)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
#endif // 0
/////////////////////////////////////////////////////////////////////////////
// ThreadFunc member functions
//获得某个线程要写入文件的开始位和文件块大小
void GetBeginPos(int TotalThreads,int ThreadIndx,long file_length,long &BgPos,long &BlkSize)
{
long BlockSize,lastBlockSize,BeginPos;
//获得平均文件大小
BlockSize=file_length/TotalThreads;
lastBlockSize=file_length;
BeginPos=0;
//获得第ThreadIndx块文件的开始位和大小
for(int i=1;i<=lastBlockSize-1;i++)
{
lastBlockSize=lastBlockSize-BlockSize;
BeginPos+=BlockSize;
}
//如果是文件最后一块,取得最后一块大小
if(ThreadIndx==TotalThreads)
{
BgPos=BeginPos;
BlkSize=lastBlockSize;
}
else
{
BgPos=BeginPos;
BlkSize=BlockSize;
}
return;
}
//监视线程
DWORD WINAPI MonitorFunc(LPVOID lpParameter)
{
//等待所有线程文件发送完成
WaitForMultipleObjects(NumOfThread,hEvent,true,INFINITE);
AfxMessageBox("文件发送完毕!!!");
return 1;
}
//发送数据线程
DWORD WINAPI SendThreadFunction(void *pParam)
{
int idx=(int)pParam;
//调用文件发送函数
SendThread(idx+1);
return 1;
}
//发送数据函数
void SendThread(int idx)
{
CFile file;
char data[ReadSize];
//文件起始位和文件块大小
long BeginPos,Size;
long FileLength;
long ReadOnce,LeftToRead,count;
//以共享和读方式大开文件
if(!file.Open(fn,CFile::modeRead|CFile::shareDenyNone))
{
AfxMessageBox("Read file error");
return;
}
FileLength=(long)file.GetLength();
sendSockets[idx-1].Send(&FileLength,4);
WaitForSingleObject(hMessageSend[idx-1],2000);
sendSockets[idx-1].Send(fn,40);
//获得文件起始位和文块大小
GetBeginPos(NumOfThread,idx,FileLength,BeginPos,Size);
//定位到文件开始位
file.Seek(BeginPos,CFile::begin);
LeftToRead=Size;
//读取文件并发送文件块
while(LeftToRead>0)
{
ReadOnce=(LeftToRead>ReadSize?ReadSize:LeftToRead);
count=file.Read(data,ReadOnce);
WaitForSingleObject(hMessageSend[idx-1],20);
//发送文件块
while(SOCKET_ERROR==sendSockets[idx-1].Send(data,count))
{
}
LeftToRead=LeftToRead-count;
}
//关闭文件
file.Close();
//设置文发送完成事件对象,表示本线程块发送完成
SetEvent(hEvent[idx-1]);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -