在win32中执行线程的步骤

时间:2013-12-16 00:07:19

标签: c++ multithreading winapi

我有两个函数,我需要并行运行它们,所以我在main函数中为它们创建了线程。代码如下所示:

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
......

     _beginthread(ModbusRead,0,(void*)12); 
     _beginthread(ModbusWrite,0,(void*)10);
}

这两个功能是ModbusRead和ModbusWrite。

我在我的代码中只实现了这两行线程,并且它们与主函数的主线程并行运行这两个函数。

让我们说功能ModbusRead在thread1中,ModbusWrite在thread2中。我必须做以下。

function ModbusWrite(thread2)
{
     if (condition1 true)
     {
         Pause thread1(donot run function ModbusRead)

         if(condition2 true)
               {
                   resume thread1(restart function ModbusRead)
               }
     }
}

由于我是线程的新手,我是在徘徊,无论我的线程实现是否正确,我如何才能满足上述条件。

1 个答案:

答案 0 :(得分:0)

Thread1必须是一个循环,每次循环检查一个事件。未设置事件时,线程将挂起在WaitForSingleObject。

while (WAIT_OBJECT_0 == WaitForSingleObject(hEvent, INFINITE))
{
   ...do some thread work
}

其他线程最初使用CreateEvent,然后使用SetEvent或ResetEvent来恢复/暂停thread1。线程不会立即暂停:只有当它的循环返回到WaitForSingleObject时才会暂停。

在实践中,您可能还需要一种在线程退出时发出信号的方法。这可以通过使用WaitForMultipleObjects来完成,其中一个事件用于恢复/暂停,另一个事件用于退出。