_beginthread

De RAD Studio
Aller à : navigation, rechercher

Remonter à Process.h - Index


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.

Remarque :  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 <stdio.h>
#include <errno.h>
#include <stddef.h>     /* _threadid variable */
#include <process.h>    /* _beginthread, _endthread */
#include <time.h>       /* 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;
}

Portability

POSIX Win32 ANSI C ANSI C++

+