2016-06-12 142 views
-3

關閉線程我必須做這個條件的線程內循環:需要幫助的C++

while(running) 

running是定點布爾變量設置爲true

但是當我點擊在一個按鈕(Qt -> QPushButton)上,它調用一個函數(pause())並且running必須設置爲false

我線程的代碼如下所示:

DWORD CServeurTcp::ClientThread(SOCKET soc, BluetoothThread *_bt) 
{ 
    ifstream fichier("test.txt", ios::in); 
    string ligne, mess_crypt, donnees, cut; 
    int compteurReception = 0; 

    if(fichier) 
    { 
     while(running) 
     { 
      if((_bt->getReception() != 0)&&(compteurReception != _bt->getReception())) 
      { 
       compteurReception = _bt->getReception(); 

       getline(fichier, ligne); 
       cut = ligne.substr (0,12); 
       cryp->vigenere_crypter(cut,mess_crypt,"VIGE"); 
       donnees = salle + " - " + mess_crypt; 
       emis = send(soc, donnees.c_str(), strlen(donnees.c_str()), 0); 
       if(emis == SOCKET_ERROR) 
        Affiche_Erreurs(WSAGetLastError()); 
       else 
        cout << "Nombre de caracteres envoyes: " << strlen(donnees.c_str()) << endl; 
      } 
     Sleep(1000); 
     } 
     fichier.close(); 
    } 
    else 
    cout << endl << "Impossible d'ouvrir le fichier !" << endl; 

    ExitThread(0); 

    return 0; 
} 

這裏是類:

class CServeurTcp; 

struct thread_param_client{ 
    CServeurTcp* cli; 
    SOCKET soc; 
    BluetoothThread *_bt; 
}; 

class CServeurTcp 
{ 
private: 
    SOCKET client; 
    int erreur, emis, recus; 
    bool running; 
    DWORD ClientThread(SOCKET, BluetoothThread*); 
    string salle; 

    Vigenere *cryp; 
    BluetoothThread *_bth; 

public: 
    CServeurTcp(string, unsigned short, string, BluetoothThread*); 
    ~CServeurTcp(); 
    int pause(); 

static DWORD WINAPI ThreadLauncher_client(void *p) 
{ 
    struct thread_param_client *Obj = reinterpret_cast<struct thread_param_client*>(p); 
    CServeurTcp *s = Obj->cli; 
    return s->ClientThread(Obj->soc,Obj->_bt); 
} 
}; 

pause()方法來設置running爲false,然後停止線程的循環,但它沒有工作... 我怎麼能做到這一點?

(關閉線程的循環,關閉它,當我打電話pause()

感謝

+1

你知道互斥體嗎? – deviantfan

+0

絕對不是:s – Adson

+4

那麼,那麼你知道下一步該學什麼:)這是線程問題之一。 – deviantfan

回答

4

running不是原子的,也不符合一個互斥體保護,因此從多個線程訪問它是不是安全,你的程序有一個數據競賽 - 因此它的行爲是不確定的,你可以不假設其結果。

+0

對不起,但我不明白你的意思:s 我的程序是一個服務器,* running * attribut允許我在停止時乾淨地停止服務器。實際上,它等待循環的結束退出。 – Adson

+1

然後閱讀C++內存模型以及std :: atomic和std :: mutex。 –