CreateThread() 多线程函数

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

参考

CreateThread给线程函数传递的参数 - 曦花 - 博客园

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WX Chen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值