传说中的路痴 发表于 2016-6-14 10:37:31

C++如何向线程函数传递多个参数?


我们先来看一个简单的程序:

#include <stdio.h>
#include <windows.h>

DWORD WINAPI ThreadFun(LPVOID pM)
{
        printf("%s\n", pM);
        return 0;
}

int main()
{
        printf("main thread\n");
        HANDLE handle = CreateThread(NULL, 0, ThreadFun, "hello world", 0, NULL);
        CloseHandle(handle);

        Sleep(2000);

        return 0;
}


在主线程中,传递给线程函数ThreadFun的串为"hello world". 受CreateThread函数的限制,只能传递LPVOID, 糟糕了,如果你要传递很多东东给子线程, 那么,该怎么办呢?请看下面的程序:

#include <stdio.h>
#include <windows.h>

typedef struct test
{
        int n;
        char c;
        char a;
}Test;

DWORD WINAPI ThreadFun(LPVOID pM)
{
        Test *pt = (Test *)pM;
        printf("%d, %c, %s\n", pt->n, pt->c, pt->a);
        return 0;
}

int main()
{
        printf("main thread\n");

        Test t;
        t.n = 1;
        t.c = 'x';
        memset(t.a, 0, sizeof(t.a));
        strncpy(t.a, "so great", sizeof(t.a) - 1);
        HANDLE handle = CreateThread(NULL, 0, ThreadFun, (LPVOID)&t, 0, NULL);
        CloseHandle(handle);

        Sleep(2000);

        return 0;
}

这种方式,无处不在,无处不见。

疯狂黑客 发表于 2016-6-15 19:47:23

好厉害啊:)

wanxia 发表于 2016-6-19 08:38:46


看到此贴!我乐了~~

wdpforinter 发表于 2016-6-21 08:35:18

其实没必要这么麻烦,用
std::thread t(std::bind(fun,参数1,参数2,参数3,....)) 就可以了:lol:lol:lol

wanxia 发表于 2016-6-23 09:58:55


挽尊~~挽尊~~挽尊~~

wanxia 发表于 2016-6-24 08:43:21


我就是来看看~么么哒~~
页: [1]
查看完整版本: C++如何向线程函数传递多个参数?