如何给线程函数 beginthread 和 pthread_create 传递参数

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,以上代码未进行测试,可能会存在一些语法小错误。

你可能感兴趣的:(JOIN,thread,c,测试,null,Integer)