我的程序有問題。我希望它有兩個線程,其中一個正在監聽連接,另一個正在從它們那裏接收數據......不幸的是,它的行爲很奇怪。它會在代碼中無處不在我的cout和cin用法,所以我甚至不能調試它。請問有人對此有所瞭解?先謝謝你。多線程將無法正常工作
#include <windows.h>
#include <iostream.h>
#include <string.h>
#include <cstdlib>
int ConnectionNum, Port=4673;
WSADATA wsaData;
SOCKET Connections[256];
DWORD WINAPI ReceiveThread(LPVOID iValue)
{
//this is going to be receiving TCP/IP packets, as soon as the connection works
}
DWORD WINAPI ListenThread(LPVOID iValue) //this thread is supposed to listen for new connections and store them in an array
{
SOCKET ListeningSocket;
SOCKET NewConnection;
SOCKADDR_IN ServerAddr;
SOCKADDR_IN ClientAddr;
int ClientAddrLen;
WSAStartup(MAKEWORD(2,2), &wsaData);
ListeningSocket=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
ServerAddr.sin_family=AF_INET;
ServerAddr.sin_port=htons(Port);
ServerAddr.sin_addr.s_addr=htonl(INADDR_ANY);
bind(ListeningSocket, (SOCKADDR*)&ServerAddr, sizeof(ServerAddr));
if(listen(ListeningSocket, 5)!=0)
{
cout << "Could not begin listening for connections.";
return 0;
}
ConnectionNum=0;
while(ConnectionNum<256)
{
Connections[ConnectionNum]=accept(ListeningSocket, (SOCKADDR*)&ClientAddr, &ClientAddrLen);
ConnectionNum++;
cout << "New connection.";
}
}
int main()
{
HANDLE hThread1,hThread2;
DWORD dwGenericThread;
char lszThreadParam[3];
hThread1=CreateThread(NULL, 0, ListenThread, &lszThreadParam, 0, &dwGenericThread);
if(hThread1==NULL)
{
DWORD dwError=GetLastError();
cout<<"SCM:Error in Creating thread"<<dwError<<endl ;
return 0;
}
hThread2=CreateThread(NULL, 0, ReceiveThread, &lszThreadParam, 0, &dwGenericThread);
if(hThread2==NULL)
{
DWORD dwError=GetLastError();
cout<<"SCM:Error in Creating thread"<<dwError<<endl ;
return 0;
}
system("pause"); //to keep the entire program from ending
}
有什麼奇怪的行爲? – Alon 2009-11-30 12:28:55
它忽略了代碼中的所有cout和cin調用,它根本不會調用它們。我在主函數的開頭放了一個cout和一個cin,它也沒有出現。 – 2009-11-30 12:33:49