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

Вниз

Завершение потока   Найти похожие ветки 

 
DDA   (2004-01-16 13:06) [0]

создаю поток


hThread := BeginThread(nil, 0, @RunningLine, nil, 0, idThread);



//-------
function RunningLine(Arg: Pointer): Integer;
begin
///...
end;
//-------


А его завершать надо или нет
Или когда поток закончится он сам завершится

Да ,кстати,а как ещё приоритет потоку этому поставить


 
Digitman   (2004-01-16 13:24) [1]


> А его завершать надо или нет


не надо
в первом приближении можно сказать, что поточная ф-ция RunningLine() автоматически и нормально завершится либо по достижению в ходе выполнения оператора END либо при выполнении в ее теле (в любом месте) оператора EXIT


 
Piter   (2004-01-16 13:46) [2]

Надо же, а я и не знал про такую функцию - BeginThread

Только не понял, что за параметр Parameter: Pointer? Для чего он?

И еще интересно, при таком создании потока как синхронизировать? Да и переменные для каждого потока как объявлять? В смысле что у TThread у каждого экземпляра свой набор данных, а тут как?


 
DDA   (2004-01-16 13:49) [3]

А кто знает как приоритет поставить?


 
mrcat   (2004-01-16 13:53) [4]

DDA © (16.01.04 13:49)
А заглянуть в Classes, где имеется реализация TThread ?


 
Digitman   (2004-01-16 13:59) [5]


> как приоритет поставить?


см. SetThreadPriority()


> Piter © (16.01.04 13:46) [2]


класс TThread (использующий как раз BeginThread) значительно облегчает программирование и управление потоками, избавляя от необходимости понимать и контролировать параметры, а так же от необходимости выполнять массу рутинных прогр.действий при необ ходимости синхронизации с другими потоками


 
AKul   (2004-01-16 14:02) [6]


> DDA © (16.01.04 13:49) [3]
> А кто знает как приоритет поставить?


API: SetThreadPriority(Handle,Priority);
Для TThread: .SetPriority(Priority);


> Piter © (16.01.04 13:46) [2]
> Надо же, а я и не знал про такую функцию - BeginThread

BeginThread - это надстройка над CreateThread (т.е. BeginThread вызывает CreateThread с переданными параметрами)


 
Piter   (2004-01-16 14:07) [7]

Понятно, а что все таки делает Parameter: Pointer?
Я по справке как-то не очень понял... куда он указывает?


 
DDA   (2004-01-16 14:11) [8]

а что писать вместо Priority в
SetThreadPriority(Handle,Priority);

ни одна из этих tpIdle, tpLowest, tpLower, tpNormal, tpHigher, tpHighest,
tpTimeCritical
не работает.
Любое число что-ли ставить?


 
Тимохов   (2004-01-16 14:12) [9]

А как ты полял, что не работает?


 
DDA   (2004-01-16 14:14) [10]

написал

hThread := BeginThread(nil, 0, @RunningLine, nil, 0, idThread);
SetThreadPriority(idThread,tplower);

говорит

[Error] Unit2.pas(4252): Incompatible types: "Integer" and "TThreadPriority"

Ну типа не совместимы


 
Тимохов   (2004-01-16 14:18) [11]

Юзай одну из след. констант.

HREAD_PRIORITY_ABOVE_NORMAL
THREAD_PRIORITY_BELOW_NORMAL
THREAD_PRIORITY_HIGHEST
THREAD_PRIORITY_IDLE
THREAD_PRIORITY_LOWEST
THREAD_PRIORITY_NORMAL
THREAD_PRIORITY_TIME_CRITICAL

Определены в windows.pas.

Почаще заглядывай в F1
SetThreadPriority+F1
Инфа оттуда...


 
DDA   (2004-01-16 14:28) [12]

это я из справки и взял
tpIdle, tpLowest, tpLower, tpNormal, tpHigher, tpHighest,
tpTimeCritical

написал SetThreadPriority
нажал F1
появилось
------------->
procedure SetThreadPriority(AThread: TThread; const APriority: TThreadPriority);

Parameters

AThread: TThread

The thread to be updated.

const APriority: TThreadPriority

The thread priority value to be used for the thread.

Description

SetThreadPriority is a procedure used to update the priority of the thread in AThread to the value specified in APriority.
SetThreadPriority encapsulates the platform-specific procedures and functions used to update the priority of a thread. For the Windows platform, Priority is a published property of TThread.
Note: Since only root is allowed to adjust thread priorities on the Linux platform, calls to SetThreadPriority are ignored regardless of login context.
------------------------
там нажал на TThreadPriority

появилось
---------->
Identifies thread priority constants.

TThreadPriority = (tpIdle, tpLowest, tpLower, tpNormal, tpHigher, tpHighest, pTimeCritical);

Description

TThreadPriority is an enumerated type that identifies the valid thread priority constant values on the Linux platform.
--------------
что я и пытался написать
tpIdle, tpLowest, tpLower, tpNormal, tpHigher, tpHighest, pTimeCritical


 
Тимохов   (2004-01-16 14:31) [13]

Там два варианта должно появляться.

Если у тебя нет, то привожу текст хелпа.
(Модератор, прости)
Вообще это winapi функция.
Пользуйся TThread.

The SetThreadPriority function sets the priority value for the specified thread. This value, together with the priority class of the thread"s process, determines the thread"s base priority level.

BOOL SetThreadPriority(

HANDLE hThread, // handle to the thread
int nPriority // thread priority level
);


Parameters

hThread

Identifies the thread whose priority value is to be set.
Windows NT: The handle must have the THREAD_SET_INFORMATION access right associated with it. For more information, see Thread Objects.

nPriority

Specifies the priority value for the thread. This parameter can be one of the following values:

Priority Meaning
THREAD_PRIORITY_ABOVE_NORMAL Indicates 1 point above normal priority for the priority class.
THREAD_PRIORITY_BELOW_NORMAL Indicates 1 point below normal priority for the priority class.
THREAD_PRIORITY_HIGHEST Indicates 2 points above normal priority for the priority class.
THREAD_PRIORITY_IDLE Indicates a base priority level of 1 for IDLE_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, or HIGH_PRIORITY_CLASS processes, and a base priority level of 16 for REALTIME_PRIORITY_CLASS processes.
THREAD_PRIORITY_LOWEST Indicates 2 points below normal priority for the priority class.
THREAD_PRIORITY_NORMAL Indicates normal priority for the priority class.
THREAD_PRIORITY_TIME_CRITICAL Indicates a base priority level of 15 for IDLE_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, or HIGH_PRIORITY_CLASS processes, and a base priority level of 31 for REALTIME_PRIORITY_CLASS processes.


Return Values

If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Every thread has a base priority level determined by the thread"s priority value and the priority class of its process. The system uses the base priority level of all executable threads to determine which thread gets the next slice of CPU time. Threads are scheduled in a round-robin fashion at each priority level, and only when there are no executable threads at a higher level does scheduling of threads at a lower level take place.
The SetThreadPriority function enables setting the base priority level of a thread relative to the priority class of its process. For example, specifying THREAD_PRIORITY_HIGHEST in a call to SetThreadPriority for a thread of an IDLE_PRIORITY_CLASS process sets the thread"s base priority level to 6. For a table that shows the base priority levels for each combination of priority class and thread priority value, see the SetPriorityClass function.

For IDLE_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, and HIGH_PRIORITY_CLASS processes, the system dynamically boosts a thread"s base priority level when events occur that are important to the thread. REALTIME_PRIORITY_CLASS processes do not receive dynamic boosts.
All threads initially start at THREAD_PRIORITY_NORMAL. Use the GetPriorityClass and SetPriorityClass functions to get and set the priority class of a process. Use the GetThreadPriority function to get the priority value of a thread.

Use the priority class of a process to differentiate between applications that are time critical and those that have normal or below normal scheduling requirements. Use thread priority values to differentiate the relative priorities of the tasks of a process. For example, a thread that handles input for a window could have a higher priority level than a thread that performs intensive calculations for the CPU.
When manipulating priorities, be very careful to ensure that a high-priority thread does not consume all of the available CPU time. A thread with a base priority level above 11 interferes with the normal operation of the operating system. Using REALTIME_PRIORITY_CLASS may cause disk caches to not flush, hang the mouse, and so on.

See Also

GetPriorityClass, GetThreadPriority, SetPriorityClass


 
Digitman   (2004-01-16 14:36) [14]


> DDA © (16.01.04 13:06)
> создаю поток


могу я полюбопытствовать, чем обосновано твое стремление работы с потоками непосредственно на WinAPI, а не с использованием удобной оболочкой в виде TThread, предоставляемой Борландом ?


 
DDA   (2004-01-16 14:44) [15]

так одной строкой

hThread := BeginThread(nil, 0, @RunningLine, nil, 0, idThread);

а так нет
там какие то execute всякие ,privatы какие то

TMyThread1 = class(TThread)
private
{ Private declarations }
protected
procedure DoWork;
procedure Execute; override;
end;

TMyThread2 = class(TThread)
private
{ Private declarations }
protected
procedure DoWork;
procedure Execute; override;
end;

var Form1: TForm1;
T1 : TMyThread1;
T2 : TMyThread2;

implementation

procedure TMyThread1.Execute;
begin
{Пока процесс не прервали, выполняем DoWork}
while not Terminated do
Synchronize(DoWork);
end;

procedure TMyThread2.Execute;
begin
{Пока процесс не прервали, выполняем DoWork}
while not Terminated do
Synchronize(DoWork);
end;

procedure TMyThread1.DoWork;
begin
{Пытаемся победить второй процесс :-)}
Form1.CheckBox1.Checked := True;
end;

procedure TMyThread2.DoWork;
begin
{Пытаемся победить первый процесс :-)}
Form1.CheckBox1.Checked := False;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
{Если кнопка называется Stop...}
if Button1.Caption = "Stop" then begin
{Прерываем оба процесса}
T1.Terminate;
T2.Terminate;
{Изменяем название кнопки}
Button1.Caption := "Start";
{Выходим из процедуры}
Exit;
end;
{Создаем и сразу запускаем два процесса}
T1 := TMyThread1.Create(False);
T2 := TMyThread2.Create(False);
{Здесь можно поэкспериментировать с приоритетами:
T1.Priority := tpLowest;
T2.Priority := tpHighest;
}
{Переименовываем кнопку}
Button1.Caption := "Stop";
end;



 
Тимохов   (2004-01-16 14:45) [16]

Флаг вам, ув. автор, как говорится в руки.

Но все-таки подумайте...


 
DDA   (2004-01-16 14:51) [17]

Кстати,как правильно будет
так
hThread := BeginThread(nil, 0, @RunningLine, nil, 0, idThread);
SetThreadPriority(hThread,THREAD_PRIORITY_BELOW_NORMAL);

или

hThread := BeginThread(nil, 0, @RunningLine, nil, 0, idThread);
SetThreadPriority( idThread,THREAD_PRIORITY_BELOW_NORMAL);


 
Digitman   (2004-01-16 14:56) [18]


> DDA © (16.01.04 14:44) [15]


> так одной строкой


.. и то тебе непонятной


> а так нет
> там какие то execute всякие ,privatы какие то


но ведь описание есть ! в хэлпе !

а вот в форме, на которую ты батоны. вероятно, кидал до сего дня не задумываясь, в ее классе тоже "privatы какие то" есть ... это же тебя не смущает ? почему тогда "privatы" в TThread тебя так мучают ? объясни ...


 
DDA   (2004-01-16 14:59) [19]

Кстати,как правильно будет
так
hThread := BeginThread(nil, 0, @RunningLine, nil, 0, idThread);
SetThreadPriority(hThread,THREAD_PRIORITY_BELOW_NORMAL);

или

hThread := BeginThread(nil, 0, @RunningLine, nil, 0, idThread);
SetThreadPriority(hThread,THREAD_PRIORITY_BELOW_NORMAL);


 
DDA   (2004-01-16 15:04) [20]

Чтобы писать в Privat-ы и Protect-ы
надо знать и понимать что пишешь
а мне (покрайне мере сейчас)не до этого чтоб разбирать что там да как

а тут написал одной строкой и не думаешь ни очем ,занимаешься
основной поставленой для себя задачей
(в будущем как - нибудь ,может быть, займусь пониманием)


 
panov   (2004-01-16 15:06) [21]

Правильно - SetThreadPriority(hThread,THREAD_PRIORITY_BELOW_NORMAL);

И не забывай освобождать дескрипторы - CloseHandle(hThread).


 
DDA   (2004-01-16 15:10) [22]

panov © (16.01.04 15:06) [21]

А когда освобождать.
Перед тем как закончится сам поток Что ли-перед End; в самом потоке ?
Если нет то надо будет тогда следить когда он завершиться?


 
panov   (2004-01-16 15:32) [23]

Если тебе не нужен дескриптор потока для дальнейшего использования, то можешь освобождать сразу. На работу потока это не повлияет.


 
Тимохов   (2004-01-16 15:34) [24]

Автору
А синхронизацией ты сам будешь заниматься?


 
DDA   (2004-01-16 15:39) [25]

panov © (16.01.04 15:32) [23] Спасибо

Тут у меня ещё вопрос


if SetThreadPriority(hThread,THREAD_PRIORITY_BELOW_NORMAL)=false
then showmessage("error");

почему у меня всегда Error

пишу так


hThread := BeginThread(nil, 0, @RunningLine, nil, 0, idThread);
if SetThreadPriority(hThread,THREAD_PRIORITY_BELOW_NORMAL)=false
then showmessage("error");


 
panov   (2004-01-16 15:59) [26]

Вызови после SetThreadPriority(hThread,THREAD_PRIORITY_BELOW_NORMAL)

ShowMessage(SysErrorMessage(getlasterror));


 
Digitman   (2004-01-16 16:50) [27]


> DDA © (16.01.04 15:04) [20]
> Чтобы писать в Privat-ы и Protect-ы
> надо знать и понимать что пишешь


т.е. можно сделать вывод, что классы ObjectPascal ты не используешь ни в коем виде в принципе ?



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

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

Наверх





Память: 0.53 MB
Время: 0.008 c
3-93350
sergg
2004-01-03 14:02
2004.01.29
Указание пути для ADO-таблиц


1-93476
_dEMOn
2004-01-15 20:46
2004.01.29
ListBox.Items


14-93663
Knight
2004-01-07 20:11
2004.01.29
Canon i250 + XP Pro


1-93570
Drakon
2004-01-16 23:18
2004.01.29
Стиль Windows XP в Delphi 8 for .Net


1-93484
race1
2004-01-15 17:05
2004.01.29
canvas.textrect





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