读书人

请教小弟我在程序2main函数中定义的a

发布时间: 2013-08-25 10:49:56 作者: rapoo

请问我在程序2main函数中定义的a ,在线程中能直接用吗?
************************************************************************
程序1

#include<stdio.h>
#include<pthread.h>

void *thread1(void *a)
{
//int a=1;
int d=(int)a;
int b=2;
int c=d+b;
printf("%d",c);
}

int main()
{
pthread_t thread;
int a=1;
pthread_create(&thread,NULL,thread1,(void*)a);
pthread_join(thread,NULL);
}


********************************************************************
程序2

#include<stdio.h>
#include<pthread.h>

void *thread1()
{
// int a=1;
int b=2;
int c=a+b;
printf("%d",c);
}

int main()
{
pthread_t thread;
int a=1;
pthread_create(&thread,NULL,thread1,NULL);
pthread_join(thread,NULL);
}


[解决办法]
当然不能用,要么在main外定义成全局变量,要么通过参数传递到线程函数,要么自己把线程封装成1个类,把参数传递给类的成员变量,然后在线程函数中调用。

读书人网 >C语言

热点推荐