控制Thread执行数目的尝试

// ThreadCountDlg.cpp : implementation file
HANDLE Event = 0;

BOOL CThreadCountDlg::OnInitDialog()
{

 Event = ::CreateEvent(NULL, TRUE, FALSE, "VVVV");
 CreateThread(NULL, 0, Count1, 0,0, 0);
    HANDLE h2 = CreateThread(NULL, 0, Count2, 0,0, 0);
 SetThreadPriority(h2, THREAD_PRIORITY_ABOVE_NORMAL);
 return TRUE;  // return TRUE  unless you set the focus to a control
}


DWORD WINAPI CThreadCountDlg::Count1(LPVOID l)
{
 static int Count = 0 ;
 while( TRUE) {
  WaitForSingleObject(Event, INFINITE);
  ResetEvent(Event);
  Count++;
  char BUF[100];
  sprintf(BUF, "I'm No 1 ---- %d/n", Count);
  OutputDebugString(BUF);
  
 }
 return 0;
}

DWORD WINAPI CThreadCountDlg::Count2(LPVOID l)
{
 static int Count = 0;
 while( TRUE ) {
  WaitForSingleObject(Event, INFINITE);
  ResetEvent(Event);
  Count++;
  char BUF[100];
  sprintf(BUF, "I'm No 2 ---- %d/n", Count);
  OutputDebugString(BUF);
  
 }
 return 0;
}

void CThreadCountDlg::OnButton1()
{
 // TODO: Add your control notification handler code here
 SetEvent(Event);
}
 
dlg初始化的时候生成两个thread,为了保证某个时间点上只有一个在工作,用event来控制,获取时间片后立刻把event置为nonsignal

你可能感兴趣的:(控制Thread执行数目的尝试)