请问一个多线程问题:
我在三个线程里都同时用到了 同一个全局变量,是不是一定要加上 synchronize 呀???
可是加上后,程序每隔20秒左右会停住(感觉运行不过来一样),五六秒之后就又正常了,这样一直运行着;
如果不用synchronize 的话运行时正常,可是线程会在运行几十次之后就停止啦。
我在线程里加了sleep(15000);对那个全局变量,有读和写的操作。
我在三个线程里都同时用到了 同一个全局变量,是不是一定要加上 synchronize 呀???
可是加上后,程序每隔20秒左右会停住(感觉运行不过来一样),五六秒之后就又正常了,这样一直运行着;
如果不用synchronize 的话运行时正常,可是线程会在运行几十次之后就停止啦。
我在线程里加了sleep(15000);对那个全局变量,有读和写的操作。
解决方案 »
- 请教 各位大哥,怎么取的 sql server 服务器 的名字(如 lsh\lsh2004)?谢谢!
- 转帖:中国现状--一个浙大教授的演讲(让人痛心疾首)
- DELPHI开发中能否将JPEG图片保存到ORACLE数据库内,如何保存?
- Gauss-Jordan Method
- 那位仁兄知道《delphi的原子世界》一书在那里可以找到,他的出版社是那一家,作者是谁。
- 关于事件的响应
- DBGRID的picklist問題,在线等!
- 如何在richedit中显示big5和日文字?望赐教!
- 何处能找到delphi函数的详细说明?最好是中文的
- 菜鸟请教,100分送上,请高手指点
- 数据库更新问题
- 请教,如何剪辑AVI文件中的一段,另存为一新的AVI文件?
你代码有问题,帖出来看看
1、定义:
FLock: TRTLCriticalSection;2、初始化:
InitializeCriticalSection(FLock);
FList := TStringlist.Create;
3、使用互斥临界
EnterCriticalSection(FLock);
FList.Add(p);
LeaveCriticalSection(FLock);4、删除临界
DeleteCriticalSection(FLock);
private
FList: TList;
FLock: TRTLCriticalSection;
FDuplicates: TDuplicates;
public
constructor Create;
destructor Destroy; override;
procedure Add(Item: Pointer);
procedure Clear;
function LockList: TList;
procedure Remove(Item: Pointer);
procedure UnlockList;
property Duplicates: TDuplicates read FDuplicates write FDuplicates;
end;
{ TThreadList }constructor TThreadList.Create;
begin
inherited Create;
InitializeCriticalSection(FLock);
FList := TList.Create;
FDuplicates := dupIgnore;
end;destructor TThreadList.Destroy;
begin
LockList; // Make sure nobody else is inside the list.
try
FList.Free;
inherited Destroy;
finally
UnlockList;
DeleteCriticalSection(FLock);
end;
end;procedure TThreadList.Add(Item: Pointer);
begin
LockList;
try
if (Duplicates = dupAccept) or
(FList.IndexOf(Item) = -1) then
FList.Add(Item)
else if Duplicates = dupError then
FList.Error(@SDuplicateItem, Integer(Item));
finally
UnlockList;
end;
end;procedure TThreadList.Clear;
begin
LockList;
try
FList.Clear;
finally
UnlockList;
end;
end;function TThreadList.LockList: TList;
begin
EnterCriticalSection(FLock);
Result := FList;
end;procedure TThreadList.Remove(Item: Pointer);
begin
LockList;
try
FList.Remove(Item);
finally
UnlockList;
end;
end;procedure TThreadList.UnlockList;
begin
LeaveCriticalSection(FLock);
end;
关于synchronize ,更多的是用在和VCL界面的同步,他通过消息的形式,使得方法在主线程内执行
临界区和青互斥体Mutex有什么不同么?