If-else statements won't work

时间:2016-04-15 11:11:01

标签: c++ multithreading

I am trying to make a communication between two simultaneously running threads through a global variable.

char dir='w'; //global var


UINT EditDir ( LPVOID pParam);//accepts dir from user in a loop
UINT Move ( LPVOID pParam);   //processes dir (its incomplete)

int main()
{
    ........
    ........
    CWinThread* pThread1 = AfxBeginThread(EditDir,(LPVOID)NULL);
    CWinThread* pThread2 = AfxBeginThread(Move,(LPVOID)NULL);
    WaitForSingleObject(pThread1, INFINITE);
    ........
    ........
}

UINT EditDir(LPVOID pParam)
{
    bool end=false; 
    while (!end)
    {
        ::dir = getchar();
        Sleep(10);
        if (::dir=='q')end=true;//***************************************
    }
return 0;
}

UINT Move ( LPVOID pParam)
{
    //process dir in a loop
    return 0;
}

The if statement in while loop doesn't work its like the compiler removes the line before compilation.

after I press q the loop should end but it keeps on going.

Where am I wrong ?

2 个答案:

答案 0 :(得分:0)

该代码可能会出现很多问题。

  • 编译器可能会对其进行优化,以便将dir存储在寄存器中而不会反映到其他函数中。
  • 编译器或处理器可能会重新排序会导致某些奇怪行为的语句。
  • 编写别名(您的代码写入恰好位于dir旁边的其他变量,处理器优化写入以使用块,有效地覆盖目录)。
  • 凭空结果。
  • 点击持有不同值的低级别(L1)缓存。

等等。

您需要使用线程安全的构造。至少使用std :: atomic来防止写入别名和其他一些非线程安全的编译器优化。 您还可以添加互斥锁以保护对变量的访问。

可能最好的设置是,如果一个线程从输入中读取char并将副本推送到生产者 - 消费者队列或通过通过良好测试且维护良好的库中的通信通道。

答案 1 :(得分:0)

最后,我发现了错误........

CWinThread* pThread2 = AfxBeginThread(Move,(LPVOID)NULL);//  #1
WaitForSingleObject(pThread1, INFINITE);  //                 #2

pThread是一个类的对象.......不是句柄和

WaitForSingleObject(HANDLE hHandle,DWORD dwMilliSeconds)// needs a handle  

所以我们在第1行和第2行之间做的是

HANDLE hThread;
hThread=pThread->m_hThread;  

并在WaitForSingleObject(...)中传递hThread而不是pThread。

相关问题