API HOOK如何防止多线程访问?看很多文章都说用临界区来防止多线程,但不知道该如何应用在API HOOK中? 请各位大侠指点。

解决方案 »

  1.   

    [email protected]
    谢谢啊, :)
      

  2.   

    不是不是,我发搞错了.我的意思是指在API HOOK中的多线程.呵呵
      

  3.   

    代码就一个窗体,我就不发了,贴出来:
    unit Cthread;interfaceuses
      Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
      StdCtrls;type
      TForm1 = class(TForm)
        Button1: TButton;
        Edit1: TEdit;
        procedure Button1Click(Sender: TObject);
        procedure FormDestroy(Sender: TObject);
      private
      public
        { Public declarations }
      end;var
      Form1: TForm1;
      ThreadHandle: THandle;                 // holds the handles the the threads
      ThreadHandle2: THandle;
      CriticalSection: TRTLCriticalSection;  // holds the critical section infoimplementation{$R *.DFM}Function ThreadFunc(Info: Pointer): Integer; stdcall;
    Var
      Count : Integer;    // general loop control variable
    Begin
      {performing the EnterCriticalSection function prevents the second thread
       from executing until this thread leaves the critical section}
      EnterCriticalSection(CriticalSection);  {show a visual display}
      for Count := 0 to 100 Do
      begin
        Form1.Edit1.Text := IntToStr(Count);
        Sleep(1);
      end;  {display a message}
      Form1.Edit1.Text := 'Hello from the thread!';  {pause for a second}
      Sleep(1000);  {leave the critical section and exit the thread}
      LeaveCriticalSection(CriticalSection);
      ExitThread(4);
    end;procedure TForm1.Button1Click(Sender: TObject);
    var
      ThreadId1, ThreadId2: DWORD;   // holds the created thread identifiers
    begin
      {initialize the critical section information}
      InitializeCriticalSection(CriticalSection);  {create and execute the first thread}
      ThreadHandle := CreateThread(nil, 0, @ThreadFunc, nil, 0, ThreadId1);  {create and execute the second thread}
      ThreadHandle2 := CreateThread(nil, 0, @ThreadFunc, nil, 0, ThreadId2);
    end;procedure TForm1.FormDestroy(Sender: TObject);
    begin
      {we are done, so destroy the critical section information}
      DeleteCriticalSection(CriticalSection);
    end;end.
      

  4.   

    应该在Hook当中是一样地使用,基本上就是通过InitializeCriticalSection初始化一个TRTLCriticalSection对象,然后在你需要同步的函数的入口调用EnterCriticalSection,在出口调用LeaveCriticalSection。