从线程和RS 232调用函数

时间:2017-07-19 09:30:58

标签: c++ multithreading serial-port

我在控制台应用程序中使用Visual Studio 2008进行编程。我正在使用由Rs 232传达的显示器。

我的线程数从0到10秒。当达到10我想关闭显示器背光。为此,我有一个从线程调用的函数。从线程调用很好,因为我知道函数的代码被执行。

但是当从线程调用该函数时,关闭背光的代码不起作用,并且它从另一个地方调用它。有任何想法吗? 感谢。

void FunctionBacklightoff(HANDLE portHandle,DWORD bytesTransmitted)
{
    cout << "backoff";
    WriteFile(portHandle, backlight_off , 4, &bytesTransmitted, NULL);//does not work when 
    //it is called from the thread. It works when it is called from wmain()
}

DWORD WINAPI solo_thread(void* arg)
{ 
   int Counter = 0;
   printf( "In second thread...\n" );

   while ( true )
   {
       if(Counter<10)
       {
           Counter++;
           Sleep(1000);
       }
       else 
       {
           printf( "Han pasado 10 segundos; Counter:-> %d\n", Counter );
           FunctionBacklightoff(portHandle,bytesTransmitted);//from here doesnt work
           Counter = 0;
       }

   }

return 0;
}

int wmain(void)
{
    hThread =CreateThread(NULL, 0, solo_thread,NULL ,0, NULL);
    //inicialize rs232 communications...
    retVal = PortOpen(&portHandle, 115200);
    if (!retVal)
    {
        printf("Could not open CoM port");
        getchar();
    }   
    else
    {

        printf("CoM port opened successfully");
        retVal = FALSE;
    }
    FunctionBacklightoff(portHandle,bytesTransmitted);//from here works
}

1 个答案:

答案 0 :(得分:0)

如何声明portHandle?看起来它是静态字段,因此线程可能根本无法在创建后发生变化。确保您可以将portHandle标记为volatile或更改操作顺序:

//Open port so we will be sure that postHandle is populated before thread starts.
retVal = PortOpen(&portHandle, 115200);
hThread = CreateThread(NULL, 0, solo_thread,NULL ,0, NULL);

你还有一个BUG,你的wmain会在执行线程之前退出。要解决这个问题,您应该在wmain最后一个括号之前放置以下代码:

WaitForSingleObject(hThread, INFINITE);

请注意,由于您的线程有while(true)没有中断条件,它将永远运行,每10秒将关闭背光。如果这不是故意的,请在其他地方添加break