c++

C++多线程beginthread()函数怎么使用

小亿
97
2024-01-19 01:53:15
栏目: 编程语言

_beginthread()函数是C语言中的多线程创建函数,用于创建一个新的线程。以下是_beginthread()函数的使用方法:

#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;
}

在上面的示例中,我们首先包含了<process.h>头文件,然后定义了一个子线程函数ThreadFunc。在main()函数中,我们调用_beginthread()函数创建了一个新线程,并将子线程函数ThreadFunc作为参数传递给它。_beginthread()函数的第一个参数是要执行的子线程函数,第二个参数是堆栈大小(0表示使用默认堆栈大小),第三个参数是传递给子线程函数的参数。_beginthread()函数返回一个句柄,可以用于后续操作。

在主线程中,我们使用_endthreadex()函数等待子线程结束。然后,主线程输出一条消息并退出。

请注意,_beginthread()函数是C语言的函数,因此在C++中使用时需要包含<process.h>头文件,并使用std::coutstd::cerr输出消息。另外,_beginthread()函数返回的句柄可以用于后续操作,例如等待线程结束或关闭线程句柄等。

0
看了该问题的人还看了