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