首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

请教小弟我在程序2main函数中定义的a ,在线程中能直接用吗

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

请问我在程序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个类,把参数传递给类的成员变量,然后在线程函数中调用。

热点排行