据我所知,可以使用指向结构的指针。但是我想知道,还有没有更有效或更优雅的方法呢?至少在使用结构时,不容易看到函数使用的参数是什么。
感谢您提供有见地的答案。
这是一个小示例,它使用WIN32 API:
#include <windows.h>
#include <stdio.h>
struct PARAMS
{
int i;
char* msg;
};
DWORD WINAPI myThread(void* parameter)
{
PARAMS* params = (PARAMS*)parameter;
printf("Received parameters: i = %d, msg = '%s'\n", params->i, params->msg);
return 0;
}
int main(int argc, char* argv[])
{
char msg[] = "Hi there.";
PARAMS params;
params.i = 1;
params.msg = msg;
HANDLE threadHandle = CreateThread(NULL, 0, myThread, ¶ms, 0, NULL);
WaitForSingleObject(threadHandle, INFINITE);
return 0;
}
您说,“要查看函数使用的参数并不容易”。那么这取决于情况。如果您认为它“不够优雅”,那么至少应该在这里留下一些有用的评论……如果您使用良好的命名并尝试编写代码,这是自我说明,那么使用结构就可以了。
这里是包装CreateThread的示例,以便使用您的代码的程序员不必知道您正在使用某种结构:
#include <windows.h>
#include <stdio.h>
class MyWrapper
{
private:
struct PARAMS
{
int i;
char* msg;
};
static DWORD WINAPI myThread(void* parameter)
{
PARAMS* params = (PARAMS*)parameter;
printf("Received parameters: i = %d, msg = '%s'\n", params->i, params->msg);
delete params;
return 0;
}
public:
HANDLE createThread(int i, char* msg)
{
PARAMS* params = new PARAMS;
params->i = i;
params->msg = msg;
return CreateThread(NULL, 0, MyWrapper::myThread, params, 0, NULL);
}
};
int main(int argc, char* argv[])
{
MyWrapper mw;
char msg[] = "Hi there.";
HANDLE threadHandle = mw.createThread(1, msg);
WaitForSingleObject(threadHandle, INFINITE);
return 0;
}
这里是一个小示例,如果您想将单个参数传递给Win32 API中的线程函数,则>]
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>
DWORD WINAPI funHello(void *x)
{
int c = (int*)x;
printf("\n Thread No: %d\n",c);
// Do some work , call some function, etc.
return 0;
}
int main()
{
HANDLE myhandle;
DWORD threadId;
int c = 1;
myhandle = CreateThread(NULL, 0, funHello, (void *)c, 0, &threadId);
if (myhandle == NULL)
{
printf("Create Thread Failed. Error no: %d\n", GetLastError);
}
WaitForSingleObject(myhandle, INFINITE);
printf("\n Main Hello...\n");
CloseHandle(myhandle);
return 0;
}