如何使用多线程锁定资源



我有一个属性表,其中有四个页面。在第二个页面中,我拥有一个列表控件和一个按钮。在第二个页面中,我创建了两个线程。当我在第一个页面中单击"下一步"时,我正在尝试用从网络中检索到的一些值枚举列表控件。因此,在这里,搜索对话框和枚举列表是在两个并行运行的不同线程中处理的。在页面的前面弹出搜索对话框,在后台检索网络中的值,并用这些值枚举列表。在那段时间里,如果我点击客户端区域,那么这个搜索对话框就会最小化。但这不应该发生,除非搜索对话框被关闭,否则我不能访问父窗口(与ModalDiaolg框相同的情况,正如我们所知,除非子窗口被关闭,我们将无法访问父窗口,类似的情况对我来说也是必要的。)这是我为一次运行这些线程所做的代码。

    BOOL CModelSelectionView::CreateModelThread()
        {
               unsigned threadID;
          if( NULL == ( m_hModelThread = (HANDLE)_beginthreadex(
                       NULL,
                        0,
                       &CModelSelectionView::ModelThreadProc,
                       reinterpret_cast<void*>(this),
                       0,
                       &threadID)) )
      {
               return FALSE;
      }

      return TRUE;
     }

//该线程用于搜索对话框

    UINT CModelSelectionView::ModelThreadProc( void* lpContext )
    {
     CModelSelectionView *pSelectModelFromList = 
      reinterpret_cast<CModelSelectionView*> (lpContext);`
      AfxSetResourceHandle(theApp.m_hDialogResource);
      CSearchingView SearchView(IDD_DIALOG_SEARCH);
     INT nRes = SearchView.DoModal();
    ::CloseHandle( pSelectModelFromList->m_hModelThread );
     pSelectModelFromList->m_hModelThread = NULL;
    _endthreadex( 0 );

 return TRUE;
}
BOOL CModelSelectionView::CreateInstallerThread()
{
    unsigned threadID;
if( NULL == ( m_hInstallerThread = (HANDLE)_beginthreadex(
    NULL,
    0,
    &CModelSelectionView::InstallerThreadProc,
    reinterpret_cast<void*>(this),
    0,
    &threadID)) )
{
    return FALSE;
}
return TRUE;
}

//用一些值初始化列表的第二个线程

UINT CModelSelectionView::InstallerThreadProc( void* lpContext )
{
    CModelSelectionView *pSelectModelFromList = 
    reinterpret_cast<CModelSelectionView*> (lpContext);
    pSelectModelFromList->m_listCtrl.DeleteAllItems();
    LVITEM lvitem;
    lvitem.mask = LVIF_TEXT;
    lvitem.iItem = 0;
    lvitem.iSubItem = 0;
    lvitem.pszText = L"";
    lvitem.cchTextMax = sizeof(lvitem.pszText);
    int nItem = pSelectModelFromList->m_listCtrl.InsertItem(&lvitem);
    ::Sleep(200);
    pSelectModelFromList->m_listCtrl.SetItemText(0,1,L"XXX");
    pSelectModelFromList->m_listCtrl.SetItemText(0,2,L"YYY");
    pSelectModelFromList->m_listCtrl.SetItemText(0,3,L"ZZZ");
    pSelectModelFromList->m_listCtrl.SetItemText(0,4,L"AAAA");

::Sleep(200);

::TerminateThread(pSelectModelFromList->m_hModelThread, 0);
    ::CloseHandle(pSelectModelFromList->m_hModelThread );
    pSelectModelFromList->m_hModelThread = NULL;
    ::CloseHandle( pSelectModelFromList->m_hInstallerThread );
    pSelectModelFromList->m_hInstallerThread = NULL;
    _endthreadex( 0 );
    return TRUE;
}

除非关闭搜索对话框,否则不应允许它访问父窗口。例如,当单击一个按钮时,对于该按钮处理程序,我正在调用domodal,然后会出现一个子对话框弹出窗口,除非我们关闭该对话框,否则我们将不被允许访问父权限,类似地,在这种情况下,我也必须这样做。

有人能建议我如何做到这一点吗。

有人能告诉我如何

Simply EnableWindow(FALSE)用于不应接收任何输入的窗口。它仍将被显示,其内容也将更新,但鼠标和键盘事件将不会到达此窗口。

最新更新