傳遞參數的兩種方法
線程函數只有一個參數的情況:直接定義一個變量通過應用傳給線程函數。
例子
#include
#include
using namespace std;
pthread_t thread;
void * fn(void *arg)
{
int i = *(int *)arg;
cout<<"i = "<<i<<endl;
return ((void *)0);
}
int main()
{
int err1;
int i=10;
err1 = pthread_create(&thread, NULL, fn, &i);
pthread_join(thread, NULL);
}
操作系統以進程為單位分配資源。
線程是執行單位,線程函數有多個參數的情況:這種情況就必須申明一個結構體來包含所有的參數,然后在傳入線程函數。
具體請查看代碼:
Mularg.c
#include
#include
#include
#include
typedef struct arg_struct ARG ;
struct arg_struct {
char name[10] ;
int age ;
float weight ;
} ;
void * thfn ( void * arg )
{
ARG * p = (ARG *) arg ;
printf( " name is : %s , age is : % d , weight is : %f \ n " , p->name , p->age , p->weight ) ;
return NULL ;
}
int main(int argc , char *argv [ ] )
{
pthread_t tid ;
ARG arg ;
int err ;
strcpy ( arg.name , " zhanggd " ) ;
arg.age = 26 ;
arg.weight = 70 ;
err = pthread_create ( &tid , NULL , thfn , (void *) & arg ) ;
if( err != 0 ) {
printf( " can’ˉt create thread %s\n", strerror(err) ) ;
exit(1);
}
return 0 ;
}
程序執行結果:

原文鏈接:http://www.maiziedu.com/wiki/process/pass/
