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 ?
答案 0 :(得分:0)
该代码可能会出现很多问题。
等等。
您需要使用线程安全的构造。至少使用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。