最简单多线程程序

//#include "StdAfx.h"
#include <windows.h> //使用多线程必须的
#include <iostream> //这是观看效果用的
using namespace std;

DWORD WINAPI MTOne(LPVOID param);
DWORD WINAPI MTTwo(LPVOID param);

DWORD WINAPI MTOne(LPVOID param){
  while(true)
  {
    Sleep(1000);
    cout<<"12 "<<endl;
  }
  //一旦返回,这个线程就结束了。
  return 0;
}
DWORD WINAPI MTTwo(LPVOID param){
  while(true)
  {
    Sleep(1000);
    cout<<"ab "<<endl;
  }
  return 0;
}

int main(int argc, char* argv[])
{
  int inp=0;
  HANDLE hand=CreateThread (NULL, 0, MTOne, (void*)&inp, CREATE_SUSPENDED, NULL);
  HANDLE hand2=CreateThread (NULL, 0, MTTwo, (void*)&inp, CREATE_SUSPENDED, NULL);
  while(true){
    cin>>inp;
    if(inp==1) //运行线程
    {
      ResumeThread(hand);
      ResumeThread(hand2);
    }
    else //暂停线程
    {
      SuspendThread(hand);
     SuspendThread(hand2);
    }
  };
  //终止线程
  TerminateThread(hand,1);
  TerminateThread(hand2,1);

  return 0;
}
在MFC中,线程被分为两类,即工作线程用户界面线程

#include <windows.h> #include <iostream.h> DWORD WINAPI Fun1Proc( LPVOID lpParameter // thread data ); DWORD WINAPI Fun2Proc( LPVOID lpParameter // thread data ); int index=0; int tickets=100; HANDLE hMutex; void main() { HANDLE hThread1; HANDLE hThread2; hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL); hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL); CloseHandle(hThread1); CloseHandle(hThread2); /*while(index++<1000) cout<<"main thread is running"<<endl;*/ //hMutex=CreateMutex(NULL,TRUE,NULL); hMutex=CreateMutex(NULL,TRUE,"tickets"); if(hMutex) { if(ERROR_ALREADY_EXISTS==GetLastError()) { cout<<"only instance can run!"<<endl; return; } } WaitForSingleObject(hMutex,INFINITE); ReleaseMutex(hMutex); ReleaseMutex(hMutex); Sleep(4000); // Sleep(10); } DWORD WINAPI Fun1Proc( LPVOID lpParameter // thread data ) { /*while(index++<1000) cout<<"thread1 is running"<<endl;*/ /*while(TRUE) { //ReleaseMutex(hMutex); WaitForSingleObject(hMutex,INFINITE); if(tickets>0) { Sleep(1); cout<<"thread1 sell ticket : "<<tickets--<<endl; } else break; ReleaseMutex(hMutex); }*/ WaitForSingleObject(hMutex,INFINITE); cout<<"thread1 is running"<<endl; return 0; } DWORD WINAPI Fun2Proc( LPVOID lpParameter // thread data ) { /*while(TRUE) { //ReleaseMutex(hMutex); WaitForSingleObject(hMutex,INFINITE); if(tickets>0) { Sleep(1); cout<<"thread2 sell ticket : "<<tickets--<<endl; } else break; ReleaseMutex(hMutex); }*/ WaitForSingleObject(hMutex,INFINITE); cout<<"thread2 is running"<<endl; return 0; }  

你可能感兴趣的:(thread,多线程,null,iostream,fun,winapi)