线程同步的简单例子

Delphi:

program Threads;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  Windows;

var
  iCounter,nRetCode,n: Integer;
  criCounter: TRTLCriticalSection ;
  hThread: array[0..2] of THandle;
  hEvents: array[0..2] of THandle;
  iParams: array[0..2] of Integer;

function threadA(pD:Pointer):DWORD;stdcall;
var iID,i,iCopy:Integer;
begin
 iID:=Pinteger(pD)^;
 for i:=0 to 1 do
 begin
  EnterCriticalSection(criCounter);
  iCopy :=iCounter;
  Sleep(100);
  iCounter:=iCopy+1;
  Writeln(Format('thread %d : %d/n',[iID,iCounter]));
  LeaveCriticalSection(criCounter);
 end;
  Writeln(Format('Envent id: %d',[iID]));
  SetEvent(hEvents[iID]);
 Result:=0;
end;

begin
  iCounter:=0;
  nRetCode:=0;
  begin

  //创建临界区
  InitializeCriticalSection(criCounter);
  //创建线程
  for n:=0 to 2 do
  begin
      hEvents[n]:=CreateEvent(nil,True,False,'');
      iParams[n]:=n;
      CreateThread(nil,0,@threadA,@iParams[n],0,hThread[n]);
  end;
  //等待线程结束
  WaitForMultipleObjects(3,@hEvents,TRUE,INFINITE);//hEvent一定要为定维数组
  DeleteCriticalSection(criCounter);
  WriteLn('/nover/n');
  end;
end.

 

int iCounter=0;
CRITICAL_SECTION criCounter;
int iParams[3];

DWORD WINAPI threadA(void* pD)
{
 int iID=(int)pD;
 for(int i=0;i<8;i++)
 {
  EnterCriticalSection(&criCounter);
  int iCopy=iCounter;
  Sleep(100);
  iCounter=iCopy+1;
  printf("thread %d : %d/n",iID,iCounter);
  LeaveCriticalSection(&criCounter);
 }
 return 0;
}

CWinApp theApp;

using namespace std;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
 int nRetCode = 0;

 // initialize MFC and print and error on failure
 if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
 {
  // TODO: change error code to suit your needs
  cerr << _T("Fatal Error: MFC initialization failed") << endl;
  nRetCode = 1;
 }
 else
 {
  //创建临界区
  InitializeCriticalSection(&criCounter);
  //创建线程
  HANDLE hThread[3];
  /*
  CWinThread* pT1=AfxBeginThread((AFX_THREADPROC)threadA,(void*)1);
  CWinThread* pT2=AfxBeginThread((AFX_THREADPROC)threadA,(void*)2);
  CWinThread* pT3=AfxBeginThread((AFX_THREADPROC)threadA,(void*)3);
  hThread[0]=pT1->m_hThread;
  hThread[1]=pT2->m_hThread;
  hThread[2]=pT3->m_hThread;
  */

  for(int i=0;i<3;i++)
  {
   CreateThread(NULL,0,&threadA,&i,CREATE_SUSPENDED,(unsigned long*)&hThread[i]);
   ResumeThread(hThread[i]);
  }
 
  //等待线程结束
  WaitForMultipleObjects(3,hThread,TRUE,INFINITE);
  DeleteCriticalSection(&criCounter);
  printf("/nover/n");
 }

 return nRetCode;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值