2016-06-12 108 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。 –