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

 

posted @ 2015-05-17 20:26  杀死比特  阅读(1658)  评论(0编辑  收藏  举报