На главную

On-line справка по Win32 API

Написать письмо
БЕСПЛАТНАЯ ежедневная online лотерея! Выигрывай каждый день БЕСПЛАТНО!
Список всех статей A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z | Скачать Вниз

CreateThread



The CreateThread function creates a thread to execute within the address space of the calling process.

HANDLE CreateThread(

LPSECURITY_ATTRIBUTES lpThreadAttributes, // pointer to thread security attributes
DWORD dwStackSize, // initial thread stack size, in bytes
LPTHREAD_START_ROUTINE lpStartAddress, // pointer to thread function
LPVOID lpParameter, // argument for new thread
DWORD dwCreationFlags, // creation flags
LPDWORD lpThreadId // pointer to returned thread identifier
);


Parameters

lpThreadAttributes

Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If lpThreadAttributes is NULL, the handle cannot be inherited.

Windows NT: The lpSecurityDescriptor member of the structure specifies a security descriptor for the new thread. If lpThreadAttributes is NULL, the thread gets a default security descriptor.
Windows 95: The lpSecurityDescriptor member of the structure is ignored.

dwStackSize

Specifies the size, in bytes, of the stack for the new thread. If 0 is specified, the stack size defaults to the same size as that of the primary thread of the process. The stack is allocated automatically in the memory space of the process and it is freed when the thread terminates. Note that the stack size grows, if necessary.
CreateThread tries to commit the number of bytes specified by dwStackSize, and fails if the size exceeds available memory.

lpStartAddress

The starting address of the new thread. This is typically the address of a function declared with the WINAPI calling convention that accepts a single 32-bit pointer as an argument and returns a 32-bit exit code. Its prototype is:

DWORD WINAPI ThreadFunc( LPVOID );

lpParameter

Specifies a single 32-bit parameter value passed to the thread.

dwCreationFlags

Specifies additional flags that control the creation of the thread. If the CREATE_SUSPENDED flag is specified, the thread is created in a suspended state, and will not run until the ResumeThread function is called. If this value is zero, the thread runs immediately after creation. At this time, no other values are supported.

lpThreadId

Points to a 32-bit variable that receives the thread identifier.



Return Values

If the function succeeds, the return value is a handle to the new thread.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
Windows 95: CreateThread succeeds only when it is called in the context of a 32-bit program. A 32-bit DLL cannot create an additional thread when that DLL is being called by a 16-bit program.

Remarks

The new thread handle is created with full access to the new thread. If a security descriptor is not provided, the handle can be used in any function that requires a thread object handle. When a security descriptor is provided, an access check is performed on all subsequent uses of the handle before access is granted. If the access check denies access, the requesting process cannot use the handle to gain access to the thread.
The thread execution begins at the function specified by the lpStartAddress parameter. If this function returns, the DWORD return value is used to terminate the thread in an implicit call to the ExitThread function. Use the GetExitCodeThread function to get the thread's return value.

The CreateThread function may succeed even if lpStartAddress points to data, code, or is not accessible. If the start address is invalid when the thread runs, an exception occurs, and the thread terminates. Thread termination due to a invalid start address is handled as an error exit for the thread's process. This behavior is similar to the asynchronous nature of CreateProcess, where the process is created even if it refers to invalid or missing dynamic-link libraries (DLLs).

The thread is created with a thread priority of THREAD_PRIORITY_NORMAL. Use the GetThreadPriority and SetThreadPriority functions to get and set the priority value of a thread.
When a thread terminates, the thread object attains a signaled state, satisfying any threads that were waiting on the object.
The thread object remains in the system until the thread has terminated and all handles to it have been closed through a call to CloseHandle.

The ExitProcess, ExitThread, CreateThread, CreateRemoteThread functions, and a process that is starting (as the result of a call by CreateProcess) are serialized between each other within a process. Only one of these events can happen in an address space at a time. This means that the following restrictions hold:

· During process startup and DLL initialization routines, new threads can be created, but they do not begin execution until DLL initialization is done for the process.
· Only one thread in a process can be in a DLL initialization or detach routine at a time.
· ExitProcess does not return until no threads are in their DLL initialization or detach routines.



A thread that uses functions from the C run-time libraries should use the beginthread and endthread C run-time functions for thread management rather than CreateThread and ExitThread. Failure to do so results in small memory leaks when ExitThread is called.

See Also

CloseHandle, CreateProcess, CreateRemoteThread, ExitProcess, ExitThread, GetExitCodeThread, GetThreadPriority, ResumeThread, SetThreadPriority, SECURITY_ATTRIBUTES


Пригласи друзей и счет твоего мобильника всегда будет положительным!
Предыдущая статья
 
Сайт Народ.Ру Интернет
Следующая статья
Пригласи друзей и счет твоего мобильника всегда будет положительным!

CreateThread



Функция CreateThread создает резьбу, чтобы выполняться в пределах пространства адреса вызова процесса.

РУЧКА CreateThread(

LPSECURITY_ATTRIBUTES lpThreadAttributes, // указатель, чтобы заправлять атрибуты безопасности DWORD dwStackSize, // размера кипы начальной резьбы, в байтах LPTHREAD_START_ROUTINE lpStartAddress, // указателе, чтобы заправлять функцию LPVOID lpParameter, // аргумент для новой резьбы DWORD dwCreationFlags, // создание сигнализирует указатель LPDWORD lpThreadId // на возвращавшее идентификатор резьбы
);


Параметры

lpThreadAttributes

Указатель в структуру SECURITY_ATTRIBUTES, которая определяет может возвращанная ручка быть унаследована процессами ребенка. Если lpThreadAttributes НЕДЕЙСТВИТЕЛЕН, ручка не может быть унаследована.

Окно NT: член lpSecurityDescriptor структуры определяет дескриптор безопасности для новой резьбы. Если lpThreadAttributes НЕДЕЙСТВИТЕЛЕН, резьба получает встроенный дескриптор безопасности.
Окно 95: член lpSecurityDescriptor структуры проигнорирован.

dwStackSize

Определяет размер, в байтах, кипы для новой резьбы. Если 0 определены, размер кипы устанавливается по умолчанию в тот же размер как та самая первичная резьба процесса. Кипа распределяется автоматически в пространстве памяти процесса и она освобождена когда резьба завершается. Отметьте, что размер кипы выращивает, если необходимо.
CreateThread ПЫТАЕТСЯ совершать количество байтов определенных dwStackSize и терпит неудачу если размер превышает доступную память.

lpStartAddress

Стартовый адрес новой резьбы. Это - обычно адрес функции объявлялся WINAPI, вызывающий соглашение, которое принимает единственный 32- битовый указатель как аргумент и возвращало 32- битовый выходной код. Прототип:

DWORD WINAPI ThreadFunc( LPVOID );

lpParameter

Определяет единственную 32- битовую величину параметра пройденную в резьбу.

dwCreationFlags

Определяет дополнительные флаги, которые управляют созданием резьбы. Если флаг CREATE_SUSPENDED определен, резьба создана в приостановленном состоянии, и не будет работать пока функция ResumeThread не будет названа. Если эта величина - нуль, прогоны резьбы немедленно после создания. В на этот раз, никакие другие величины не поддерживаны.

lpThreadId

Точки на 32- битовую переменную, которые получают идентификатор резьбы.



Обратные Величины

Если функция добивается успеха, обратная величина является ручкой в новую резьбу.
Если функция терпит неудачу, обратная величина НЕДЕЙСТВИТЕЛЬНА. Для того, чтобы расширять информацию ошибки, назовите GetLastError.
Windows 95: CreateThread добивается успеха только когда приглашено контекст 32- битовой программы. 32- Бит DLL не может создать дополнительную резьбу когда это DLL назваться 16- битовой программой.

Замечания

Новая ручка резьбы создана полным доступом к новой резьбе. Если дескриптор безопасности не предусмотрен, ручка может быть использована в любой функции, которая требует объектную ручку резьбы. Когда дескриптор безопасности предусмотрен, чек доступа выполнен во всем последующем использовании ручки прежде, чем доступу предоставят. Если чек доступа запрещит доступ, запрос процесса не может использовать ручку, чтобы приобретать доступ к резьбе.
Выполнение резьбы начинается в функции определенной параметром lpStartAddress. Если эта функция возвращается, обратная величина DWORD использована, чтобы завершать резьбу на подразумевающемся вызове в функцию ExitThread. Используйте функцию GetExitCodeThread, чтобы получать обратную величину резьбы.

Функция CreateThread может добиться успеха даже если бы точки lpStartAddress на данные, код, или не доступно. Если стартовый адрес недействителен когда резьба работает, исключение происходит, и резьба завершается. Завершение Резьбы из-за неправильного стартового адреса прооперировано как выход ошибки для процесса резьбы. Это поведение подобное асинхронной природе CreateProcess, где процесс создан даже если бы эт имеет отношение к неправильной или динамической связи отсутствующих библиотек (DLLs).

Резьба создана приоритетом резьбы THREAD_PRIORITY_NORMAL. Используйте GetThreadPriority и функции SetThreadPriority, чтобы получать и устанавливать приоритетную величину резьбы.
Когда резьба завершается, объект резьбы достигает сигнального состояния, удовлетворяющего любую резьбу, которая ожидалась на объекте.
Объект резьбы остается в системе пока резьба не завершила и все ручки, чтобы закрыто через вызов на CloseHandle.

ExitProcess, ExitThread, CreateThread, Функции CreateRemoteThread, и процесс, которые запускают (как результат вызова CreateProcess), изданы сериями между друг друга в пределах процесса. Только одно из этих событий могут случиться в пространстве адреса за один раз. Это означает, что следующие ограничения держат:

В течение запуска процесса и программ инициализации DLL, новая резьба может быть создана, но они не начинают выполнение пока инициализация DLL не сделана для процесса.
Только один резьба в процессе может быть в инициализации DLL или отделять программу за один раз.
ExitProcess НЕ возвращается пока никакая резьба не будет в их инициализации DLL или отделяет программы.



Резьба, которая использует функции из времени прогона библиотек C должно использовать beginthread и endthread время прогона функций C для управления резьбы а не CreateThread и ExitThread. Невозможнось делать так результатами в небольших течах памяти когда ExitThread назван.

Смотри Также

CloseHandle, CreateProcess, CreateRemoteThread, ExitProcess, ExitThread, GetExitCodeThread, GetThreadPriority, ResumeThread, SetThreadPriority, SECURITY_ATTRIBUTES


Вверх Version 1.3, Oct 26 2010 © 2007, 2010, mrhx Вверх
 mrhx software  Русский перевод OpenGL  Русский перевод Win32 API
 
Используются технологии uCoz