How to use the C++ multithreading beginthread() function?

The _beginthread() function in C language is used to create multiple threads, allowing for the creation of a new thread. Here is the usage of the _beginthread() function:

#include <iostream>
#include <process.h> // 包含 _beginthread() 函数的头文件

// 子线程函数
void ThreadFunc(void* arg) {
    std::cout << "This is a child thread." << std::endl;
}

int main() {
    // 创建一个新线程
    unsigned int threadId;
    intptr_t handle = _beginthread(ThreadFunc, 0, nullptr);
    if (handle == -1) {
        std::cerr << "Failed to create a new thread." << std::endl;
        return 1;
    }

    // 等待子线程结束
    _endthreadex(0);

    std::cout << "Main thread exits." << std::endl;
    return 0;
}

In the example above, we first include the header file, then define a subthread function called ThreadFunc. In the main() function, we call the _beginthread() function to create a new thread, passing the subthread function ThreadFunc as a parameter. The first parameter of the _beginthread() function is the subthread function to execute, the second parameter is the stack size (0 indicates using the default stack size), and the third parameter is the argument passed to the subthread function. The _beginthread() function returns a handle that can be used for subsequent operations.

In the main thread, we use the _endthreadex() function to wait for the child thread to finish. Afterwards, the main thread outputs a message and exits.

Please note that the _beginthread() function is a C language function, so when using it in C++, you need to include the header file and use std::cout and std::cerr to output messages. Additionally, the handle returned by the _beginthread() function can be used for further operations, such as waiting for the thread to finish or closing the thread handle.

bannerAds