最近稍稍看了关于线程和同步操作的功能, 用途 以及相关函数。
尝试将之前的聊天程序做了改善,将客户端和服务器端的接收过程在 一个单独的线程去处理。
使得在建立连接后,两端可以随时发送信息给对方。
另外,对聊天内容的更新,采用临界区处理方式,避免损坏资源。
所作修改大致过程如下:
1. 创建线程,
LPTHREAD_START_ROUTINE pthreadfunc = ExtermalThreadFunc_ReceiveMsg;
g_rcvthred = CreateThread(NULL,//ignored;
0, //stack size;
pthreadfunc, //thread entry address;
(LPVOID)0, //thread function parameter;
0, //flag to control the creation of thread;
&threadid //receive thread id;
);
2.将两端接收信息的过程提取为一个单独的函数,使得其循环接收信息,
DWORD WINAPI ExtermalThreadFunc_ReceiveMsg(LPVOID n)
{
... ...
strLength = recvtimeout(g_AcceptSocket->m_hSocket,(char*)wBuffer,BUFLEN,1);
... ...
}
刚开始采用的方法为:在类中增加了接受信息的函数DWORD WINAPI CMyChatServerDlg::ThreadFunc_ReceiveMsg(LPVOID n);
定义成员函数指针pThrdFunc_RcvMsg:
DWORD (WINAPI CMyChatServerDlg::*pThrdFunc_RcvMsg)(LPVOID) = &CMyChatServerDlg::ThreadFunc_ReceiveMsg;
但在函数void CMyChatServerDlg::OnBnClickedStartchat()中创建线程后,
g_rcvthred = CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE)&pThrdFunc_RcvMsg,//this sentence can not work success;
(LPVOID)0,
0,
&threadid
);
传入的参数pThrdFunc_RcvMsg无效,猜测是域名解析导致的错误,具体原因尚待分析。
3.接收到信息之后,访问临界区,
g_CriticalSectionForReceive.Lock();
更新聊天内容,
g_CriticalSectionForReceive.Unlock();