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

Вниз

Потоки   Найти похожие ветки 

 
Чародей ©   (2006-10-19 20:43) [0]

Подскажите как сделать чтобы следующий код работал:

procedure Start;
begin
while true do
 Form1.Label1.Caption:=IntToStr(random(100));
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
htr1:=CreateThread(nil,0,@Start,nil,0,tr1);
htr2:=CreateThread(nil,0,@Start,nil,0,tr2);
end;


 
Sergey Masloff   (2006-10-19 20:44) [1]

Справку прочесть. Один раз.


 
Kolan ©   (2006-10-19 20:46) [2]

TThread?


 
Чародей ©   (2006-10-19 20:51) [3]


> Справку прочесть. Один раз.

А какой раздел?


> Kolan ©   (19.10.06 20:46) [2]
> TThread?

А что изменится? Новые классы, больше кода, и ни что не меняется


 
Eraser ©   (2006-10-19 20:51) [4]

> [0] Чародей ©   (19.10.06 20:43)

[1] + лучше BeginThread.


 
Kolan ©   (2006-10-19 20:53) [5]

С API не уверен... разве можно обращаться к VCL? Думаю - нетю


 
Leonid Troyanovsky ©   (2006-10-19 20:53) [6]


> Kolan ©   (19.10.06 20:46) [2]
> TThread?


TThread.Synchronize, forever.

--
Regards, LVT.


 
Чародей ©   (2006-10-19 20:55) [7]


> Eraser ©   (19.10.06 20:51) [4]

BeginThread в SDK нет, MSDN у меня нет :(


 
Leonid Troyanovsky ©   (2006-10-19 20:55) [8]


> Kolan ©   (19.10.06 20:53) [5]

> С API не уверен... разве можно обращаться к VCL? Думаю -
>  нетю


Можно.
Если осторожно.

--
Regards, LVT.


 
Palladin ©   (2006-10-19 20:56) [9]

очень сложно, так проще

...
const
wm_setlabelcaption=wm_user+10001;

type
 TForm1 = class(TForm)
   ...
 private
   { Private declarations }
   Procedure msgSetLabelCaption(var msg:TMessage); message wm_setlabelcaption;
  ...
 end;

...

Type
TSetLebelCaptionThread=Class(TThread)
 Protected
  Procedure Execute; Override;
End;

Procedure TSetLebelCaptionThread.Execute;
Var
s:PChar;
i:Integer;
Begin
For i:=0 to 99 Do
 Begin
  s:=PChar("Thread["+IntToStr(ThreadID)+"] Iteration["+IntToStr(i)+"] : "+IntToStr(Random(100)));
  SendMessage(Form1.Handle,wm_setlabelcaption,Integer(s),0);
  Sleep(100);
 End;
End;

Procedure TForm1.msgSetLabelCaption;
Begin
Label1.Caption:=PChar(msg.WParam);
Application.ProcessMessages;
End;

procedure TForm1.Button1Click(Sender: TObject);
Var
i:Integer;
begin
For i:=0 to 100 Do TSetLebelCaptionThread.Create(False);
end;



 
Leonid Troyanovsky ©   (2006-10-19 20:59) [10]


> Чародей ©   (19.10.06 20:55) [7]

> BeginThread в SDK нет, MSDN у меня нет :(


Delphi help, RTFM.

--
Regards, LVT.

ЗЫ А, воо-ще, есть http://www.msdn.microsoft.com


 
Leonid Troyanovsky ©   (2006-10-19 21:05) [11]


> Palladin ©   (19.10.06 20:56) [9]

>   SendMessage(Form1.Handle


Не очень, IMHO, осторожно.

--
Regards, LVT.


 
Palladin ©   (2006-10-19 21:09) [12]

это я утрировал :) конечно, гораздо интересней SendAppMessage, в Application ловить и отсылать в MainForm или куда нибудь в другое место...


 
Чародей ©   (2006-10-19 21:11) [13]

А просто подсказать в чем дело нельзя (без пересылок по далекому адресу)?
Поставил скобки CriticalSection внутрь цикла, не помогло.(Это вообще имеет отношение?)
И изменится что-либо если вместо
Form1.Label1.Caption:=IntToStr(random(100));
будет вызываться процедура из сторонней DLL?


 
MikePetrichenko ©   (2006-10-19 22:32) [14]


> А просто подсказать в чем дело нельзя (без пересылок по
> далекому адресу)?


VCL не есть потокобезопасная (thread-safe)


> Поставил скобки CriticalSection внутрь цикла, не помогло.
> (Это вообще имеет отношение?)


И не поможет. Не имеет.


> И изменится что-либо если вместо
> Form1.Label1.Caption:=IntToStr(random(100));
> будет вызываться процедура из сторонней DLL?


Да. Будет вызываться процедура из сторонней DLL.

Для случая с

> procedure Start;
> begin
> while true do
>  Form1.Label1.Caption:=IntToStr(random(100));
> end;


Нельзя из потока вызвать какие либы свойства/методы и т.п. объектов VCL. Используй либо класс TThread c его Synchronize, либо оконные сообщения, либо другие способы синхронизации с главным потоком приложения.

Хотя для лейблы подойдет и SetWindowText.


 
Amoeba ©   (2006-10-20 10:47) [15]


> Хотя для лейблы подойдет и SetWindowText.

С какой стати?


 
Чародей ©   (2006-10-20 16:35) [16]


> > Поставил скобки CriticalSection внутрь цикла, не помогло.
>
> > (Это вообще имеет отношение?)
>
> И не поможет. Не имеет.

Это только для VCL? Так как для глобального массвива, заполняемого двумя потоками, я так понял, использовать все же надо


> Хотя для лейблы подойдет и SetWindowText.

Для лабла не подходит, но я заменил на StaticText

> BeginThread

Нигде не нашел ни полсловечка про функцию. Если просто заменить то не передаются параметры. Или для неё надо использовать не stdcall?


 
Пусик ©   (2006-10-20 16:41) [17]


> Нигде не нашел ни полсловечка про функцию.


Spawns a separate thread of execution.

Unit

System

Category

thread management routines

function BeginThread(SecurityAttributes: Pointer; StackSize: LongWord; ThreadFunc: TThreadFunc; Parameter: Pointer; CreationFlags: LongWord; var ThreadId: LongWord): Integer;

Description

Use this routine or a TThread object to spawn separate threads of execution instead of calling the CreateThread Win32API directly. BeginThread encapsulates the Win32 CreateThread API call, but unlike CreateThread, it sets the global IsMultiThread variable, thereby making the heap thread-safe.

BeginThread takes a normal Pascal function as the thread function. Thread functions should handle all of their own exceptions. BeginThread sets up an exception frame that allows the system"s default exception handler to catch any of the thread"s exceptions that have not been handled.

BeginThread returns the Windows thread handle.
-------------
TThreadFunc is a pointer to the starting address of a routine for a new thread of execution.

Unit

System

type TThreadFunc = function(Parameter: Pointer): Integer;

Description

The TThreadFunc type defines a type of routine that is the starting address for a new thread of execution. A TThreadFunc routine is passed to the Delphi routine BeginThread or the Windows API CreateThread function. When BeginThread executes, TThreadFunc acts as the entry point for the new thread.

The Parameter pointer passed to the BeginThread routine is passed directly to the thread function. Parameter can be a single 32-bit value or a 32-bit pointer to other data. The value in Parameter can be used within the TThreadFunc routine.

TThreadFunc returns the value of the thread entry point procedure. This result is usually passed to the EndThread routine. An application can retrieve the TThreadFunc return value by calling the Windows API GetExitCodeThread function.


 
Чародей ©   (2006-10-20 16:51) [18]


> Пусик ©   (20.10.06 16:41) [17]

Спасибо, большинство вопросов отпало


 
MikePetrichenko ©   (2006-10-20 17:04) [19]


> С какой стати?

Бошибся, виноват.


> Для лабла не подходит, но я заменил на StaticText

Вот для нее. (лейба не окно).



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

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

Наверх





Память: 0.5 MB
Время: 0.048 c
15-1160622507
КиТаЯц
2006-10-12 07:08
2006.11.05
Задержка в пакетном файле


2-1161612005
stud
2006-10-23 18:00
2006.11.05
вечер уже ничего не понимаю, помогите!!!


2-1161596663
Ося
2006-10-23 13:44
2006.11.05
Динамически созданные СheckBox


2-1161324932
Steep
2006-10-20 10:15
2006.11.05
Строки и потоки


15-1161242512
Серьезный Сэм
2006-10-19 11:21
2006.11.05
Общий доступ





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
Английский Французский Немецкий Итальянский Португальский Русский Испанский