Create multiple threads in VC++ and their application
Creating multiple threads in VC++ can be achieved using functions provided by the Windows API. Here is a simple example code:
#include <windows.h>
#include <iostream>
using namespace std;
// 线程函数
DWORD WINAPI ThreadFunction(LPVOID lpParam) {
// 获取传入参数
int threadId = *(int*)lpParam;
// 输出线程ID
cout << "Thread " << threadId << " is running." << endl;
// 延时一段时间
Sleep(1000);
// 输出线程ID并退出
cout << "Thread " << threadId << " is exiting." << endl;
return 0;
}
int main() {
// 创建线程数组
HANDLE threads[5];
// 启动五个线程
for (int i = 0; i < 5; i++) {
// 传入参数
int* threadId = new int(i);
// 创建线程
threads[i] = CreateThread(NULL, 0, ThreadFunction, threadId, 0, NULL);
}
// 等待所有线程结束
WaitForMultipleObjects(5, threads, TRUE, INFINITE);
// 关闭线程句柄
for (int i = 0; i < 5; i++) {
CloseHandle(threads[i]);
}
return 0;
}
The above code creates five threads, each outputting their thread ID and then exiting after a delay of 1 second. In the main function, threads are created using the CreateThread function and passing the thread function and parameters. Then, the WaitForMultipleObjects function is used to wait for all threads to finish, and the CloseHandle function is used to close the thread handles.
Moreover, multithreading can be used in practical applications to enhance the concurrency and responsiveness of programs. For example, it can be employed to accelerate compute-intensive tasks and achieve parallel processing. It is important to note that synchronization and mutual exclusion between threads must be carefully managed in multithreaded programming to prevent issues such as race conditions and deadlocks.