VC中線程函數如何傳遞多個參數


我用CreateThread創建線程,它的第三個參數是線程函數地址,規定了線程函數必須是DWORD WINAPI ...(LPVOID lpParam)形式的,只能有單個參數,但是我用CreateThread創建的時候需要向線程函數傳兩個integer和兩個char*,我在CSDN上看到了用結構體,我建了一個結構LPPARAM,然后在線程函數的開頭寫了LPPARAM* _lpParam=(LPPARAM*) lpParam;但是提示說不能從void*轉換到LPPARAM*,我到底該怎么辦才能傳這4個參數?


我就不用工程了,直接用控制台寫個例子你,方法都通用:

#include "stdio.h"
#include "conio.h"
#include "windows.h"

typedef struct _THREADDATA
{
    int v1;
    int v2;
    char *pStr1;
    char *pStr2;
}*LPTHREADDATA, THREADDATA;

DWORD WINAPI ThreadProc(LPVOID lParam)
{
    LPTHREADDATA pData = (LPTHREADDATA)lParam;
    while (1)
    {
        printf("%d\t%d\t%s\t%s\n", pData->v1, pData->v2, pData->pStr1, pData->pStr2);
    }
    return 0;
}

int main()
{
    LPTHREADDATA pData = new THREADDATA;
    pData->v1 = 10;
    pData->v2 = 100;
    pData->pStr1 = "Hello";
    pData->pStr2 = "world";
    
    DWORD ThreadId;
    ::CreateThread(NULL, 0, ThreadProc, (LPVOID)pData, 0, &ThreadId);
    
    getch();
    return 0;
}

實例工程

typedef struct _THREADDATA
{
    SOCKET sConnect;
    int cid;
   
}*LPTHREADDATA, THREADDATA;


 void recvProc(LPVOID lParam);


 int main()
 {
 //=========================================
 LPTHREADDATA pData = new THREADDATA;
        pData->sConnect = sClient[clientAmount];
 pData->cid=clientAmount;

         pData->sConnect = sClient[clientAmount-1];pData->cid=clientAmount;
 //cout<<sClient[clientAmount-1]<<endl;cout<<pData->cid<<endl;
 hThread=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)recvProc, (LPVOID)pData,0,NULL);
 
 cout<<"創建線程r"<<hThread<<endl;
 cout<<"sClient:"<<sClient[clientAmount-1]<<endl;
        void recvProc(LPVOID lParam)
{
//==============================================
LPTHREADDATA ppData = (LPTHREADDATA)lParam;
SOCKET sockConnect=ppData->sConnect;
int cid=ppData->cid;

.....


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com