zz CreateThread() and _beginthread()

_beginthread

Header File

process.h

Category

Process Control Routines

Prototype

unsigned long _beginthread(void (_USERENTRY *__start)(void *), unsigned __stksize, void *__arg);

Description

Starts execution of a new thread.

Note:

The start_address must be declared to be _USERENTRY.

The _beginthread function creates and starts a new thread. The thread starts execution at start_address.

The size of its stack in bytes is stack_size; the stack is allocated by the operating system after the stack size is rounded up to the next multiple of 4096. The thread is passed arglist as its only parameter; it can be NULL, but must be present. The thread function should terminate by simply returning; the _endthread. function will be called automatically. The _endthread function will automatically close the handle, and set the return value of the thread to zero.

Either this function or _beginthreadNT must be used instead of the operating system thread-creation API function because _beginthread and _beginthreadNT perform initialization required for correct operation of the runtime library functions.

This function is available only in the multithread libraries.

Return Value

_beginthread returns the handle of the new thread. The return value is a standard Windows handle that can be used in operating system API's such as SuspendThread and ResumeThread.

On error, the function returns -1, and the global variable errno is set to one of the following values:

EAGAIN

Too many threads

EINVAL

Invalid stack size (i.e. less than 16 bytes, or equal to zero)

ENOMEM

Not enough memory

Also see the description of the Win32 API GetLastError, in the MSDN Library.

Example

/*  Use the -tWM  (32-bit multi-threaded target) command-line switch for this example  */
#include
#include
#include /* _threadid variable */
#include /* _beginthread, _endthread */
#include /* time, _ctime */
void thread_code( void *threadno)
{
time_t t;
time(&t);
printf("Executing thread number %d, ID = %d, time = %s/n",
( int)threadno, _threadid, ctime(&t));

}

void start_thread( int i)
{
int thread_id;
#if defined(__WIN32__)
if ((thread_id = _beginthread(thread_code,4096,( void *)i)) == ( unsigned long)-1)
#else
if ((thread_id = _beginthread(thread_code,4096,( void *)i)) == -1)
#endif
{
printf("Unable to create thread %d, errno = %d/n",i,errno);
return;
}
printf("Created thread %d, ID = %ld/n",i,thread_id);
}
int main( void)
{
int i;
for (i = 1; i < 20; i++)
start_thread(i);
printf("Hit ENTER to exit main thread./n");
getchar();
return 0;
}

CreateThread Function

Creates a thread to execute within the virtual address space of the calling process.

To create a thread that runs in the virtual address space of another process, use the CreateRemoteThread function.

HANDLE WINAPI CreateThread(
__in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes,
__in SIZE_T dwStackSize,
__in LPTHREAD_START_ROUTINE lpStartAddress,
__in_opt LPVOID lpParameter,
__in DWORD dwCreationFlags,
__out_opt LPDWORD lpThreadId
);
Parameters
lpThreadAttributes

A 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.

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. The ACLs in the default security descriptor for a thread come from the primary token of the creator.

Windows XP/2000:  The ACLs in the default security descriptor for a thread come from the primary or impersonation token of the creator. This behavior changed with Windows XP SP2 and Windows Server 2003. For more information, see Remarks.
dwStackSize

The initial size of the stack, in bytes. The system rounds this value to the nearest page. If this parameter is zero, the new thread uses the default size for the executable. For more information, see Thread Stack Size.

lpStartAddress

A pointer to the application-defined function to be executed by the thread. This pointer represents the starting address of the thread. For more information on the thread function, see ThreadProc.

lpParameter

A pointer to a variable to be passed to the thread.

dwCreationFlags

The 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.

If the STACK_SIZE_PARAM_IS_A_RESERVATION flag is specified, the dwStackSize parameter specifies the initial reserve size of the stack. Otherwise, dwStackSize specifies the commit size.

Windows 2000:  The STACK_SIZE_PARAM_IS_A_RESERVATION flag is not supported.
lpThreadId

A pointer to a variable that receives the thread identifier. If this parameter is NULL, the thread identifier is not returned.

Return Value

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.

Note that CreateThread 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).

Remarks

The number of threads a process can create is limited by the available virtual memory. By default, every thread has one megabyte of stack space. Therefore, you can create at most 2,028 threads. If you reduce the default stack size, you can create more threads. However, your application will have better performance if you create one thread per processor and build queues of requests for which the application maintains the context information. A thread would process all requests in a queue before processing requests in the next queue.

The new thread handle is created with the THREAD_ALL_ACCESS access right. If a security descriptor is not provided when the thread is created, a default security descriptor is constructed for the new thread using the primary token of the process that is creating the thread. When a caller attempts to access the thread with the OpenThread function, the effective token of the caller is evaluated against this security descriptor to grant or deny access.

Windows XP/2000:  If a security descriptor is not provided when the thread is created, a default security descriptor is constructed using the effective token of the thread. If the thread is impersonating another user, the thread's effective token is the impersonation token and the default security descriptor allows access only to the impersonation token's TokenDefaultDacl owner or members. If the thread is not impersonating another user, the thread's effective token is its primary token. This behavior changed starting with Windows XP SP2 and Windows Server 2003. For more information, see Thread Security and Access Rights.

The newly created thread has full access rights to itself when calling the GetCurrentThread function.

Windows Server 2003 and Windows XP/2000:  The thread's access rights to itself are computed by evaluating the primary token of the process in which the thread was created against the default security descriptor constructed for the thread. If the thread is created in a remote process, the primary token of the remote process is used. As a result, the newly created thread may have reduced access rights to itself when calling GetCurrentThread. Some access rights including THREAD_SET_THREAD_TOKEN and THREAD_GET_CONTEXT may not be present, leading to unexpected failures. For this reason, creating a thread while impersonating another user is not recommended.

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 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 in an executable that calls the C run-time library (CRT) should use the _beginthreadex and _endthreadex functions for thread management rather than CreateThread and ExitThread; this requires the use of the multi-threaded version of the CRT. If a thread created using CreateThread calls the CRT, the CRT may terminate the process in low-memory conditions.

Creating Threads

The CreateThread function creates a new thread for a process. The creating thread must specify the starting address of the code that the new thread is to execute. Typically, the starting address is the name of a function defined in the program code (for more information, see ThreadProc). This function takes a single parameter and returns a DWORD value. A process can have multiple threads simultaneously executing the same function.

The following is a simple example that demonstrates how to create a new thread that executes the locally defined function, MyThread. The creating thread uses a dynamically allocated buffer to pass unique information to each instance of the thread function.

The calling thread uses the WaitForMultipleObjects function to persist until all worker threads have terminated. The calling thread blocks while it is waiting; to continue processing, a calling thread would use WaitForSingleObject and wait for each worker thread to signal its wait object. Note that if you were to close the handle to a worker thread before it terminated, this does not terminate the worker thread. However, the handle will be unavailable for use in subsequent function calls.

#include 
 
 
  
  
#include
#include

#define MAX_THREADS 3
#define BUF_SIZE 255

typedef struct MyData {
int val1;
int val2;
} MYDATA, *PMYDATA;

DWORD WINAPI MyThread( LPVOID lpParam )
{
HANDLE hStdout;
PMYDATA pData;

TCHAR msgBuf[BUF_SIZE];
size_t cchStringSize;
DWORD dwChars;

hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
if( hStdout == INVALID_HANDLE_VALUE )
return 1;

// Cast the parameter to the correct data type.

pData = (PMYDATA)lpParam;

// Print the parameter values using thread-safe functions.

StringCchPrintf(msgBuf, BUF_SIZE, TEXT("Parameters = %d, %d/n"),
pData->val1, pData->val2);
StringCchLength(msgBuf, BUF_SIZE, &cchStringSize);
WriteConsole(hStdout, msgBuf, cchStringSize, &dwChars, NULL);

return 0;
}

int _tmain()
{
PMYDATA pData;
DWORD dwThreadId[MAX_THREADS];
HANDLE hThread[MAX_THREADS];
int i;

// Create MAX_THREADS worker threads.

for( i=0; i {
// Allocate memory for thread data.

pData = (PMYDATA) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
sizeof(MYDATA));

if( pData == NULL )
ExitProcess(2);

// Generate unique data for each thread.

pData->val1 = i;
pData->val2 = i+100;

hThread[i] = CreateThread(
NULL, // default security attributes
0, // use default stack size
MyThread, // thread function
pData, // argument to thread function
0, // use default creation flags
&dwThreadId[i]); // returns the thread identifier


// Check the return value for success.
// If failure, close existing thread handles,
// free memory allocation, and exit.

if (hThread[i] == NULL)
{
for(i=0; i {
if (hThread[i] != NULL)
{
CloseHandle(hThread[i]);
}
}
HeapFree(GetProcessHeap(), 0, pData);
ExitProcess(i);
}
}

// Wait until all threads have terminated.

WaitForMultipleObjects(MAX_THREADS, hThread, TRUE, INFINITE);

// Close all thread handles and free memory allocation.

for(i=0; i {
CloseHandle(hThread[i]);
}
HeapFree(GetProcessHeap(), 0, pData);

return 0;
}

The MyThread function avoids the use of the C run-time library (CRT), as many of its functions are not thread-safe, particularly if you are not using the multithreaded CRT. If you would like to use the CRT in a ThreadProc function, use the _beginthreadex function instead.

It is risky to pass the address of a local variable if the creating thread exits before the new thread, because the pointer becomes invalid. Instead, either pass a pointer to dynamically allocated memory or make the creating thread wait for the new thread to terminate. Data can also be passed from the creating thread to the new thread using global variables. With global variables, it is usually necessary to synchronize access by multiple threads. For more information about synchronization, see Synchronizing Execution of Multiple Threads.

The creating thread can use the arguments to CreateThread to specify the following:

  • The security attributes for the handle to the new thread. These security attributes include an inheritance flag that determines whether the handle can be inherited by child processes. The security attributes also include a security descriptor, which the system uses to perform access checks on all subsequent uses of the thread's handle before access is granted.
  • The initial stack size of the new thread. The thread's stack is allocated automatically in the memory space of the process; the system increases the stack as needed and frees it when the thread terminates. For more information, see Thread Stack Size.
  • A creation flag that enables you to create the thread in a suspended state. When suspended, the thread does not run until the ResumeThread function is called.

You can also create a thread by calling the CreateRemoteThread function. This function is used by debugger processes to create a thread that runs in the address space of the process being debugged.

        CreateThread 是一个Win 32API 函数,_beginthread 是一个CRT(C Run-Time)函数,他们都是实现多线城的创建的函数,而且他们拥有相同的使用方法,相同的参数列表。

但是他们有什么区别呢?

一 般来说,从使用角度是没有多大的区别的,CRT函数中除了signal()函数不能在CreateThread创建的线城中使用外,其他的CRT 函数都可一正常使用,但是如果在CreateThread创建的线城中使用CRT函数的话,会产生一些Memory Leak.

下面是摘自KB的原话:

SUMMARY
All C Run-time functions except the signal() function work correctly when used in threads created by the CreateThread() function. However, depending on what CRT functions are called, there may be a small memory leak when threads are terminated. Calling strlen(), for example, does not trigger the allocation of the CRT thread data-block, and calling malloc(), fopen(), _open(), strtok(), ctime(), or localtime() causes allocation of a CRT per-thread data-block, which may cause a memory leak.
MORE INFORMATION
The "Programming Techniques" manual supplied with Visual C++ 32-bit Edition states that using CreateThread() in a program that uses Libcmt.lib causes many CRT functions to fail. Actually, the only function that should not be used in a thread created with CreateThread() is the signal() function.
There are two ways to create threads. One method involves using the CRT _beginthread() or _beginthreadex() (with Visual C++ 2.0 and later); the other method involves using the CreateThread() API. All CRT functions other than the signal() function work correctly in threads created with either _beginthread() or CreateThread(). However, there are some problems involved with using CRT functions in threads created with CreateThread().
Threads that are created and terminated with the CreateThread() and ExitThread() Win32 API functions do not have memory that is allocated by the CRT for static data and static buffers cleaned up when the thread terminates. Some examples of this type of memory are static data for errno and _doserrno and the static buffers used by functions such as asctime(), ctime(), localtime(), gmtime(), and mktime(). Using CreateThread() in a program that uses the CRT (for example, links with LIBCMT.LIB) may cause a memory leak of about 70-80 bytes each time a thread is terminated.
To guarantee that all static data and static buffers allocated by the CRT are cleaned up when the thread terminates, _beginthreadex() and _endthreadex() should be used when creating a thread. The _beginthreadex() function includes the same parameters and functionality as CreateThread().
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值