孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

在使用多线程的时候,如果多线程对某个特定的公共数据或资源进行访问,需要对多线程进行协调操作,叫做线程同步。

     例如:三个线程分别循环地向ListBox中写入数据。没有进行同步时,写入的顺序是不确定的。

   {主窗体代码}  
  1. unit Unit2;  
  2.    
  3. interface  
  4.    
  5. uses  
  6.   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  
  7.   Dialogs, StdCtrls;  
  8.    
  9. type  
  10.   TForm2 = class(TForm)  
  11.     ListBox1: TListBox;  
  12.     Button1: TButton;  
  13.     procedure Button1Click(Sender: TObject);  
  14.   private  
  15.     { Private declarations }  
  16.   public  
  17.     { Public declarations }  
  18.   end;  
  19.    
  20. var  
  21.   Form2: TForm2;  
  22.    
  23. implementation  
  24.    
  25. uses MyThread;  
  26.    
  27. {$R *.dfm}  
  28.    
  29. procedure TForm2.Button1Click(Sender: TObject);  
  30. begin  
  31.   TMyThread.Create(False);  
  32.   TMyThread.Create(False);  
  33.   TMyThread.Create(False);       
  34. end;  
  35.    
  36. end.{多线程代码}  
  37. unit MyThread;  
  38.    
  39. interface  
  40.    
  41. uses  
  42.   Classes,StdCtrls,SysUtils,Windows;  
  43.    
  44. type  
  45.   TMyThread = class(TThread)  
  46.   private  
  47.     { Private declarations }  
  48.     str:String;  
  49.     procedure AddList;  
  50.   protected  
  51.     procedure Execute; override;  
  52.   end;  
  53.    
  54. implementation  
  55.    
  56. uses Unit2;  
  57.    
  58. { TMyThread }  
  59.    
  60. procedure TMyThread.AddList;  
  61. begin  
  62.   Form2.ListBox1.Items.Add(str);  
  63. end;  
  64.    
  65. procedure TMyThread.Execute;  
  66. var  
  67.   i:Integer;  
  68. begin  
  69.   { Place thread code here }  
  70.   for i := 0 to 99 do  
  71.     begin  
  72.       if not Terminated then  
  73.         begin  
  74.           str:=Format('线程ID:%d,第%d个循环。',[GetCurrentThreadId,i]);  
  75.           Synchronize(AddList);  
  76.         end;  
  77.     end;  
  78. end;  
  79.    
  80. end.   

 

三个线程根据分配到的CPU时间的顺序向ListBox中写入数据。这里的公共资源是ListBox。

可以将这个公共的冷资源比喻为一个图书馆,线程比喻为借书看书的人员。那么没有同步处理的情况下,就好像图书馆完全开放,没有人管理,每个人都可以访问这个图书馆。看起来乱糟糟的,而且当某人想借书A的话,查询的时候书A还在,当他去借的时候可能被另一人已借走。

为了更好管理的需要(某些对公共资源的访问必须逐个线程处理,才不会出错),这里就要用到同步,即查询和借书这两个步骤要一起完成,等一个人完成以后,才接受另一个人的请求。

接下来介绍线程同步的几种手段:临界区、互斥量、信号量、事件。

posted on 2012-03-06 20:34  孤独的猫  阅读(745)  评论(0)    收藏  举报