2011-03-28 15 views
-1

我正在處理多個生產者和單個消費者問題。我想要在線程函數中傳遞像1,2,3這樣的線程,以便可以根據這些編號來命名單個線程。在線程函數中傳遞整型數組

但創建線程後,計數7後崩潰的程序。我認爲問題是由於 變量nThreadNo; 如果我限制小於7的計數,它可以正常工作。但是如果我計數超過這個,它會崩潰。

void CEvent1Dlg::CreateProducerThreads() 
{ 

    try 
    { 
     nThreadNo = new int20]; 
     memset(nThreadNo,0,20); 
     if (nThreadNo ==NULL) return; 
    }catch(...) 
    { 
     MessageBox(_T("Memory allocation Failed"),_T("Thread"),1); 
     return ; 
    } 
    int i = 0; 
    for (i = 0;i<20;i++) 
    { 
     //nThreadNo = i+1; 
     nThreadNo[i] = i+1; 
     hWndProducer[i] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ProducerThrdFunc,(void*)(nThreadNo+i),0,&dwProducerThreadID[i]);  
     if (hWndProducer[i] == NULL) 
     { 
      //ErrorHandler(TEXT("CreateThread")); 
      ExitProcess(3); 
     } 
    } 
    //WaitForMultipleObjects(20,hWndProducer,TRUE,INFINITE);    
} 

DWORD WINAPI ProducerThrdFunc (LPVOID n) 
{ 
    int *nThreadNo = (int*)n;  
    char chThreadNo[33]; 
    memset(chThreadNo,0,33); 

    while(1) 
    { 
     itoa(*nThreadNo,chThreadNo,10); 
     char* pMsg1 = new char[100]; 
     char* pMsg2 = new char[100]; 
     memset(pMsg1,0,100); 
     memset(pMsg2,0,100); 

     strcpy(pMsg1,"Producer ");  
     strcat(pMsg1," Thread No:");   
     strcat(pMsg1,chThreadNo); 

     if (stThreadInfoProd.pEventQueue->AddTail(pMsg1)==TRUE) 
     { 
      strcpy(pMsg2,"Producer ");  
      strcat(pMsg2," Thread No:");   
      strcat(pMsg2,chThreadNo); 
      strcat(pMsg2," Added the Msg"); 
     } 
     else 
     { 
      strcpy(pMsg2,"Producer ");  
      strcat(pMsg2," Thread No:");   
      strcat(pMsg2,chThreadNo); 
      strcat(pMsg2,"failed to Add the Msg");  
     } 
     PostMessage(stThreadInfoProd.hWndHandle,UWM_ONUPDATEPRODUCERLIST,(WPARAM)pMsg2,0); 
     strcat(pMsg1," Adding Msg:"); 
     //PostMessage(stThreadInfoProd.hWndHandle,UWM_ONUPDATEPRODUCERLIST,(WPARAM)pMsg2,0);   
     Sleep(3000); 
    } 
    return 0; 
} 

回答

2
  1. 您歸零前20個字節的nThreadNo,不是第一20 * sizeof(int)字節你應該做。
  2. 此代碼中還有其他數組正在編入索引:hWndProducerdwProducerThreadID。這些元素是否還有足夠的元素?
+0

哦,是的,這是一個愚蠢的錯誤.thanks.it正在工作。 – 2011-03-28 13:38:46

+0

1.我認爲我在使用新的不是malloc,它會處理這些。我不確定。我正確 – 2011-03-28 13:40:19

1

CreateThread呼叫被傳遞整數值,但是該線程功能本身被處理它作爲一個指針爲整數。而不是這樣的:

int *nThreadNo = (int*)n; 

這也許應該是:

int nThreadNo = (int)n; 

編輯:我在通話更仔細地看了看,我也看到它傳遞一個整數指針。但是,該值是堆棧數據,在線程嘗試讀取它時可能不存在。因此,它應該可能只是傳遞整數值:(void*)(nThreadNo[i])

+0

在這種情況下,它會顯示類似00089的值。我猜這樣會打印內存地址 – 2011-03-28 13:35:40

0

此行

if (nThreadNo ==NULL) return; 

是毫無價值的。

現代C++中的new運算符在失敗時不會返回NULL,但會拋出異常,但即使您使用的分配器返回NULL來指示失敗,但檢測到它已爲時過晚,您已經將NULL指針傳遞給memcpy