// multi_thread.cpp
#include "multi_thread.h"
using namespace std;
// 线程函数
DWORD WINAPI ThreadProc(LPVOID lpParam)
{
MYDATA *pmd = (MYDATA *)lpParam;
cout << "val: " << pmd->val << endl;
cout << "string: " << pmd->str << endl;
return 0;
}
// 处理
void fun()
{
MYDATA mydt[MAX_THREADS];
HANDLE hThread[MAX_THREADS];
for (int i = 0; i < MAX_THREADS; i++) {
// 参数赋值
mydt[i].val = i;
mydt[i].str = "hello_" + to_string(i);
// 创建线程
hThread[i] = CreateThread(
NULL, // default security attributes
0, // use default stack size
ThreadProc, // thread function
&mydt[i], // argument to thread function
0, // use default creation flags
NULL);
if (hThread[i] == NULL) {
ExitProcess(i);
}
}
// Wait until all threads have terminated.
WaitForMultipleObjects(MAX_THREADS, hThread, TRUE, INFINITE); //这样传给回调函数的参数不用定位static或者new出来的了
// Close all thread handles upon completion.
for (int i = 0; i < MAX_THREADS; i++) {
CloseHandle(hThread[i]);
}
}
// multi_thread.h
#include <windows.h>
#include <iostream>
#include <string>
#define MAX_THREADS 2 // 线程数量
typedef struct MyData {
int val;
std::string str;
}MYDATA;
void fun();
// main.cpp
#include <time.h>
#include <iostream>
#include "multi_thread.h"
using namespace std;
int main()
{
clock_t timeBegin;
clock_t timeEnd;
timeBegin = clock();
fun();
timeEnd = clock();
cout << "Cost time: " << timeEnd - timeBegin << " ms" << endl;
return 0;
}
参考