CreateThread创建线程传递结构体参数

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>

struct ThreadParameter{
    char user[20];
    char name[20];
};

DWORD WINAPI ThreadFunction (LPVOID pParam) {
    ThreadParameter *tp = (ThreadParameter *)pParam; //强制转换参数
    char user[20];
    char pass[20];
    strcpy(user,tp->user);
    strcpy(pass,tp->name);
    printf("User = %s pass = %s \r\n",user,pass);
    return 0;
}

int main(int argc,char* argv[])
{
    ThreadParameter tp;
    if (argc < 3)
    {
        printf("Unkow options error.\r\n");
        return -1;
    }
    memset(tp.name,0,20);
    memset(tp.user,0,20);
    strcpy(tp.user,argv[1]);
    strcpy(tp.name,argv[2]);
    HANDLE threadhandle = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadFunction,&tp,0,NULL);
    if (threadhandle == INVALID_HANDLE_VALUE)
    {
        printf("Create thread error.\r\n");
        return -1;
    }
    WaitForSingleObject(threadhandle,INFINITE); //等待线程退出
    CloseHandle(threadhandle); //关闭句柄
    return 0;
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。