Главная страница
    Top.Mail.Ru    Яндекс.Метрика
Форум: "Начинающим";
Текущий архив: 2006.04.02;
Скачать: [xml.tar.bz2];

Вниз

Доступ к файлу   Найти похожие ветки 

 
KyRo   (2006-03-16 10:22) [0]

Добрый день .
У меня есть проблема и заключается она в доступе к ini файлу.
У меня есть около 30 нитей при запуске которых каждая считывает конфигурацию из файла и прописывает в нем свои параметры.
Так вот поподают моменты когда несколько потоков обращаются к файлу одновременно и в этот момент происходит ошибка (Что то вроде Unable  acces to file )что то такое.
Как мне можно избежать этой ошибки ?
И второе если я пропишу дериктиву отключающую ошибки ввода ввывода в файлы то будет ли при такой ошибки информация все равно записыватся ?


 
Рамиль ©   (2006-03-16 10:28) [1]

procedure Synchronize(Method: TThreadMethod);


 
KyRo   (2006-03-16 10:44) [2]


> Рамиль ©   (16.03.06 10:28) [1]
> procedure Synchronize(Method: TThreadMethod);

А можно что по подробней ?


 
KyRo   (2006-03-16 11:06) [3]

Есть ли у кого то описание этой процедуры , а то в делфи хелпе ни чего не написано .


 
Рамиль ©   (2006-03-16 11:22) [4]

Да все там прекрасно описано

When you use objects from the class hierarchy, their properties and methods are not guaranteed to be thread-safe. That is, accessing properties or executing methods may perform some actions that use memory which is not protected from the actions of other threads. Because of this, a main thread is set aside to access VCL and CLX objects. This is the thread that handles all Windows messages received by components in your application.

If all objects access their properties and execute their methods within this single thread, you need not worry about your objects interfering with each other. To use the main thread, create a separate routine that performs the required actions. Call this separate routine from within your thread"s Synchronize method. For example:

procedure TMyThread.PushTheButton;
begin
 Button1.Click;
end;
procedure TMyThread.Execute;
begin
 ...
 Synchronize(PushTheButton);
 ...
end;

Synchronize waits for the main thread to enter the message loop and then executes the passed method.

Note

Because Synchronize uses the message loop, it does not work in console applications. You must use other mechanisms, such as critical sections, to protect access to VCL or CLX objects in console applications.

You do not always need to use the main thread. Some objects are thread-aware. Omitting the use of the Synchronize method when you know an object"s methods are thread-safe will improve performance because you don"t need to wait for the VCL or CLX thread to enter its message loop. You do not need to use the Synchronize method for the following objects:

Data access components are thread-safe as follows: For BDE-enabled datasets, each thread must have its own database session component. The one exception to this is when you are using Microsoft Access drivers, which are built using a Microsoft library that is not thread-safe. For dbExpress, as long as the vendor client library is thread-safe, the dbExpress components will be thread-safe. ADO and InterBaseExpress components are thread-safe.
When using data access components, you must still wrap all calls that involve data-aware controls in the Synchronize method. Thus, for example, you need to synchronize calls that link a data control to a dataset by setting the DataSet property of the data source object, but you don"t need to synchronize to access the data in a field of the dataset.

For more information about using database sessions with threads in BDE-enabled applications, see Managing multiple sessions.
Controls are not thread-safe.
Graphics objects are thread-safe. You do not need to use the main VCL or CLX thread to access TFont, TPen, TBrush, TBitmap, TMetafile (VCL only), TDrawing (CLX only), or TIcon. Canvas objects can be used outside the Synchronize method by locking them.

While list objects are not thread-safe, you can use a thread-safe version, TThreadList, instead of TList.

Call the CheckSynchronize routine periodically within the main thread of your application so that background threads can synchronize their execution with the main thread. The best place to call CheckSynchronize is when the application is idle (for example, from an OnIdle event handler). This ensures that it is safe to make method calls in the background thread.


 
KyRo   (2006-03-16 11:24) [5]

Спасибо у меня что то не получилось найти , щас буду пробовать


 
KyRo   (2006-03-16 12:21) [6]

Ничего не получается .
На примере написан один параметр и єто метод которій ты сам создаеш
type
 TParsM = class(TTHread)
  private
    Nom:integer;
    FileN: array [0..29] of string;
  protected
    procedure Execute; override;
     procedure WriteIni(FileName,Section,Parametr:String;Tupe:String);
  public
    constructor Create(CreateSuspennded: Boolean; const NomHread:
                string; const FileNm:string);


Вот я создал ВРайтИни
Но потом когда из екзекут пытаюсь выполнить синхронайз оно пишет что не хватает параметров.

Я как понимаю вызывается вот эта процедура из модуля классес

class procedure TThread.Synchronize(AThread: TThread; AMethod: TThreadMethod);
var
 SyncRec: TSynchronizeRecord;
begin
 if AThread <> nil then
   AThread.Synchronize(AMethod)
 else
 begin
   SyncRec.FThread := nil;
   SyncRec.FSynchronizeException := nil;
   SyncRec.FMethod := AMethod;
   TThread.Synchronize(@SyncRec);
 end;
end;


Подскажите как мне запустить эту синхранизацию и синхронезирует ли оно мне все потоки ?


 
KyRo   (2006-03-16 13:10) [7]

У меня выдает такую ошибку кто небуть знает из за чего ?


> There is no overloaded version of "Synchronize" that can
> be called with these arguments


 
Джо ©   (2006-03-16 15:36) [8]

> [7] KyRo   (16.03.06 13:10)
> У меня выдает такую ошибку кто небуть знает из за чего ?

Из-за того, что ты передаешь неверное количество параметров (и/или они имеют неверный тип) в метод Synchronize.


 
KyRo   (2006-03-16 16:13) [9]

Все я правильно ввожу я объявил процедуру с четырьмя полями стринг и ввожу 4 поля


 
Джо ©   (2006-03-16 16:32) [10]

Какие поля? Какие процедуры? Ты о чем вообще?



Страницы: 1 вся ветка

Форум: "Начинающим";
Текущий архив: 2006.04.02;
Скачать: [xml.tar.bz2];

Наверх





Память: 0.47 MB
Время: 0.037 c
3-1139565329
Polevi
2006-02-10 12:55
2006.04.02
Приходный ордер форма № М-4


1-1140902492
Grol
2006-02-26 00:21
2006.04.02
Умолчать о ошибке после закрытия программы


15-1140694572
Praetor
2006-02-23 14:36
2006.04.02
Творческий вопрос(Нужна идея)


2-1142500422
tytus
2006-03-16 12:13
2006.04.02
BM_SETIMAGE


2-1142781071
Andrey.Ru
2006-03-19 18:11
2006.04.02
Помогите Mpeg2!!!!!!





Afrikaans Albanian Arabic Armenian Azerbaijani Basque Belarusian Bulgarian Catalan Chinese (Simplified) Chinese (Traditional) Croatian Czech Danish Dutch English Estonian Filipino Finnish French
Galician Georgian German Greek Haitian Creole Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Japanese Korean Latvian Lithuanian Macedonian Malay Maltese Norwegian
Persian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swahili Swedish Thai Turkish Ukrainian Urdu Vietnamese Welsh Yiddish Bengali Bosnian
Cebuano Esperanto Gujarati Hausa Hmong Igbo Javanese Kannada Khmer Lao Latin Maori Marathi Mongolian Nepali Punjabi Somali Tamil Telugu Yoruba
Zulu
Английский Французский Немецкий Итальянский Португальский Русский Испанский