⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tls.pas

📁 Delphi Win32核心API参考光盘源码 本书包含了常用的Windows API函数
💻 PAS
字号:
unit TLS;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Label1: TLabel;
    Label2: TLabel;
    Button2: TButton;
    Label3: TLabel;
    Label4: TLabel;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  ThreadHandle: THandle;    // holds a handle to a thread
  NDX: DWORD;               // holds the thread local storage index

implementation

{$R *.DFM}


Function ThreadFunc(Info: Pointer): Integer; stdcall;
Var
  FormDC: HDC;        // holds the forms device context
  AString: pchar;     // points to a string
Begin
  {retrieve a handle to the form's device context}
  FormDC := GetDC(Form1.Handle);

  {initialize the string}
  AString := 'Second thread';

  {place this value into the specified index of the thread local storage}
  if not(TLSSetValue(NDX, AString)) then
    ShowMessage('value not set');

  {display the value retrieved from the index of the thread local storage}
  TextOut(FormDC, 10, 50, TLSGetValue(NDX), 13);

  {display the thread local storage index}
  Form1.Label4.Caption := IntToStr(NDX);

  {release the form device context and exit the thread}
  ReleaseDC(Form1.Handle, FormDC);
  ExitThread(4);
end;

procedure TForm1.Button1Click(Sender: TObject);
Var
  ThreadId: DWORD;     // holds a thread identifier
  Value: PChar;        // points to a string
  FormDC: HDC;         // holds the form device context
begin
  {allocate a thread local storage index slot}
  NDX := TLSAlloc;

  {retrieve a handle to the form's device context}
  FormDc := GetDC(Form1.Handle);

  {create a thread}
  ThreadHandle := CreateThread(nil, 0, @ThreadFunc, nil, 0, ThreadId);

  {initialize he string}
  Value := 'Main Thread';

  {place this value into the same index of the same thread local
   storage allocated slot.  this value will be different than the
   one in the thread, although they are using the same index}
  if not(TLSSetValue(NDX, Value)) then
    ShowMessage('value not set');

  {display the value at the specified thread local storage slot}
  TextOut(FormDC, 300, 50, TLSGetValue(NDX), 11);

  {display the thread local storage index.  note that it is the
   same as reported by the thread}
  Label3.Caption := IntToStr(NDX);

  {release the form's device context}
  ReleaseDC(Form1.Handle, FormDC);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  {free the thread local storage slot}
  if not(TLSFree(NDX)) then
    ShowMessage('the TLS index was not freed')
  else
    ShowMessage('the TLS index was freed');
end;

end.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -