我的主线程往一个链表加数据
辅线程取数据
有时取出的数据不正确
如何保证数据的正确性>

解决方案 »

  1.   

    我的全局变量是一个链队列!
    有一个 EnLink(X:Byte) 表示入队
    有一个 GetLink  表示出队
    有主线程调用  EnLink
    有辅线程调用  GetLink
    我创建一个TCriticalSection对象 LockLink
    有调用EnLink 时
    LockLink.Acquire;
    try
      EnLink(X);
    finally
      LockLink.Release;
    end;
    在调用GetLink时
    LockLink.Acquire;
    try
      X := GetLink;
    finally
      LockLink.Release;
    end;
    但是还是不行,不知道我用的对不对!第一次用,请帮忙!
      

  2.   

    对相同的过程要多次调用要用同步函数!!
    由于同一时刻可以有多个线程同时运行,那么我们还必须解决好同步的问题。procedure Execute; 
      begin 
          While not Terminated do 
          begin 
             Synchronize(过程名); 
          end; 
      end; 
      

  3.   

    to RuinRice
    能不能说的详细点
    还是不大明白你的意思!var aTemp:TRecPoint;
    begin
      New(aTemp);
      aTemp^.Next := nil;
      aTemp^.Data := x;
      aLast^.Next := aTemp;
      aLast := aTemp;
    end;这是入队begin
      Result:=False;
      if aHead^.Next <> nil then
      begin
        x := aHead^.Next.Data;
        aHead^.Next := aHead^.Next^.Next;
        Result := True;
      end;
      if aHead^.Next = nil then
        aLast := aHead;
    end;这是出队
      

  4.   

    Critical Sections(临界段),源代码中如果有不能由两个或两个以上线程同时执行的部分,可以用临界段来使这部分的代码执行串行化。它只能在一个独立的进程或一个独立的应用程序中使用
    CS:TRTLCriticalSection;
    //在窗体创建中
    InitializeCriticalSection(cs)
    //在窗体销毁中
    DeleteCriticalSection(cs)
    //在线程中
    EnterCriticalSection(cs)
    ……保护的代码
    LeaveCriticalSection(cs)
      

  5.   

    用一个方法访问这个变量。
    procedure T.OperatingValue(X : Byte = 255); //x = 255表示读取,其他表示插入
    begin
      if X = 255 then 
        GetLink
      else 
        EnLink(x);
    end;调用的时候就用: 
    Synchronize(OperatingValue) ;读取
    Synchronize(OperatingValue(100)) ;插入
      

  6.   

    var aTemp:TRecPoint;
    begin
      New(aTemp);
      aTemp^.Next := nil;
      aTemp^.Data := x;
      aLast^.Next := aTemp;
      aLast := aTemp;
    end;这是入队begin
      Result:=False;
      if aHead^.Next <> nil then
      begin
        x := aHead^.Next.Data;
        aHead^.Next := aHead^.Next^.Next;
        Result := True;
      end;
      if aHead^.Next = nil then
        aLast := aHead;
    end;这是出队是不是在出队的时候报错啊?
    报的是什么错?
      

  7.   

    有时会出现  Out of system resources 的错误提示是什么的因呢?
      

  8.   

    上面说到了两种方法:Synchronize()应该是可以的,但是它占用的是主线程的时间。
    另外有种方法就是临界区的方法:
    delphi中有个组件TCriticalSection就是专门负责多线程互斥访问的。
    访问前调用enter方法;访问后调用leave方法;
    比如:
    a: TCriticalSection;
    ....a.enter;
    try
       /// visit the data.
    finally
      a.leave;
    end;