我有2个线程,第一个是:`
while(1){
if(recv(conn_s, (char*) &i, sizeof(i),0)>0){
if(i==28){
SetEvent(event);
//printf("nell if di 28\n");
HANDLE t;
sleep(1);
//TerminateThread(scegli, 0);
//if (CloseHandle(scegli)==0) printf("error close\n");
t=CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) avvia_conversazioneCl, conn, SYNCHRONIZE, 0);
WaitForSingleObject(t, INFINITE);
第二个:
const HANDLE handles[2]={event, stdinHandle};
while(1){
switch(WaitForMultipleObjects(num, handles, FALSE, 0)){
case 0:
ExitThread(-1);
break;
case 1:
r=ReadConsole(stdinHandle, &interlocutore, nLength, &charsRead, NULL);
if (r==0){
printf("%d\n", GetLastError());
}
//global_value_to_exit=1;
int size=strlen(interlocutore);
interlocutore[size-2]='\0';
int verifica=verifica_interlocutore(interlocutore);
if (verifica==0){
printf("interlocutore non disponibile, riprova: \n");
continue;
}
int rrr=send(socket, interlocutore, size, 0);
if (rrr<=0){
printf("send error\n");
}
sleep(1);
if(recv(socket, (char*) &ack, sizeof(int), 0)==SOCKET_ERROR){
printf("errore: %d\n", WSAGetLastError());
}
printf("ho ricevuto %d\n", (int) ack);
if(ack==999){
//sleep(1);
HANDLE t;
DWORD tID;
t=CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) avvia_conversazioneCl, conn_s, 0, &tID);
WaitForSingleObject(t, INFINITE);
CloseHandle(t);
//global_value_to_exit=0;
ack=0;
vis=CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) visualizza_utenti, conn_s, 0, &visID);
}
//ResetEvent(stdinHandle);
break;
case WAIT_FAILED:
perror("failed: \n");
break;
}
memset(interlocutore, 0, sizeof(interlocutore));
}
return NULL;
}
还:
const HANDLE handles[2]={event, stdinHandle};
event=CreateEvent(NULL, FALSE, FALSE, NULL);
stdinHandle=GetStdHandle(STD_INPUT_HANDLE);`
重点是: 如果我在控制台写东西我用第二个线程做事情,如果我得到28接收我想让第二个线程退出,所以我设置信号事件。在这一点上使用waitformultipleobjects我应该进入case 0并退出线程。相反,我已经recv 28并改变了事件的状态,如果我在控制台中写了一些东西,第二个线程进入案例1。 写完别的东西之后似乎已经死了
任何建议?