1. 傳遞單個參數:直接傳遞指向參數的指針。
/*----------------------- beginthread.c ----------------------------*/
#include <process.h>
void doubleNum(void* arg)
{
int *arg=(int*)arg;
*arg=(*arg)*2;
}
void main()
{
int arg = 0;
_beginthread(doubleNum,0,(void*)&arg);
}
/*----------------------- pthread_create.c ----------------------------*/
#include <pthread.h>
void doubleNum(void* arg)
{
int *arg=(int*)arg;
*arg=(*arg)*2;
}
void main()
{
int arg = 0;
pthread_t thread;
pthread_create(&thread, 0, doubleNum, (void*)&arg);
pthread_join(thread, NULL);
}
2. 傳遞多個參數:定義一個包含所有參數的結構體,傳遞指向結構體的指針。
/*----------------------- StructAndFunc.h ----------------------------*/
#include <stdio.h>
struct threadparam
{
int *arg1;
char[5] arg2;
}
void doubleNum(void* arg)
{
int *arg1=(threadparam*)arg->arg1;
char *arg2=(threadparam*)arg->arg2;
printf("integer: %d char array: %s \n", *arg1, arg2);
}
/*----------------------- beginthread.c ----------------------------*/
#include <process.h>
#include <StructAndFunc.h>
void main()
{
int integer= 5;
char[5] array={a,b,c,d,e};
threadparam* param=new threadparam();
param->arg1=&interger;
param->arg2=array;
HANDLE m_hThread = (HANDLE)_beginthread(doubleNum,0,(void*)threadparam);
}
/*----------------------- pthread_create.c ----------------------------*/
#include <pthread.h>
#include <StructAndFunc.h>
void main()
{
int integer= 5;
char[5] array={a,b,c,d,e};
threadparam* param=new threadparam();
param->arg1=&interger;
param->arg2=array;
pthread_t thread;
pthread_create(&thread, 0, doubleNum, (void*)param);
pthread_join(thread, NULL);
}
ps,以上代碼未進行測試,可能會存在一些語法小錯誤。