Chinaunix首页 | 论坛 | 博客
  • 博客访问: 589989
  • 博文数量: 197
  • 博客积分: 7001
  • 博客等级: 大校
  • 技术积分: 2155
  • 用 户 组: 普通用户
  • 注册时间: 2005-02-24 00:29
文章分类

全部博文(197)

文章存档

2022年(1)

2019年(2)

2015年(1)

2012年(100)

2011年(69)

2010年(14)

2007年(3)

2005年(7)

分类: LINUX

2012-02-29 19:30:29

  教了这么多年,帮学生调过那么多试程序,没留下任何痕迹,这里面不乏一些有趣的例子。今天帮助一个学生解决问题的时候,突然想到,把一些还算有趣的例子记录下来,倘能再活10年来看,或许有些感慨吧。
  下面经过修改后的代码来自操作系统课程设计,原来的params只是一个变量。学生的问题是:“创建了4个线程,怎么看不到4个运行",原因很简单,4个都运行了,因为共享一个params,所以互相覆盖标识,导致printf输出错误的标识误导学生,解决方式很简单,每线程一个params

void *thread_function(void *arg)
{
  struct param *dirinfo = (struct param *)arg;
  char *name;
  struct RetVal * ret=NULL;
  while(h!=NULL)
  {
/*************************************************************/
    pthread_mutex_lock(&mymutex);
    printf("I am thread %d\n",dirinfo->id);
    //  printf("%s \n",h->name);
    name=h->name;
    h=h->next;
    pthread_mutex_unlock(&mymutex);
/*************************************************************/  
    ret=Search_id_infile(dirinfo->dir,name,dirinfo->key);//在文件中查找key
//     printf("I am  %d\n",dirinfo->id);
 }
  return NULL;
}


int main(int argc,char *argv[])
{
  long thread_num=1;
  pthread_t *thread_id;
  struct param *params;//每个线程应有一个独立的拷贝

  fileName *p;
  int i,fd,f_num=0;
  char *dir,*key;
 
  if(argc==3)//启动一个线程
   {
     thread_num=1;
     dir = argv[2];    
     key=argv[1];
  }
  else if(argc==5)//启动argv[2]个线程
  {
    if(strcmp(argv[1],"-j")!=0)
      perror("Useage:idfind [-j n] id dirname");
    else
      thread_num=atoll(argv[2]);//字符串转换成整型
    dir = argv[4];
    key=argv[3];
  }
  //printf("%ld\n",thread_num);
  if((thread_id = (pthread_t*)malloc(sizeof(pthread_t)*thread_num))==NULL)
      handle_error("malloc");

  if((fd = open(argc > 1 ? dir : ".", O_RDONLY | O_DIRECTORY)) == -1)
     handle_error("open dir");
 //////////////////////////////////////////////////////////////////////////////////////
  f_num=Getdirents(fd);//获取文件目录下到所有普通文件
 //////////////////////////////////////////////////////////////////////////////////////
  close(fd);
  h=Head;
 
  thread_num = thread_num > f_num ? f_num : thread_num;
 
  if((params = (struct param*)malloc(sizeof(struct param)*thread_num))==NULL)
      handle_error("malloc params");  
 
  for(i=0;i  {
    params[i].id=i;            //线程标示符
    strcpy(params[i].dir,dir);
    strcpy(params[i].key,key);      //文件名链表头指针
  }
 
  for(i=0;i  {
    //线程执行时,传递给参数的指针指向的地址应该不同,否则将会被覆盖
    if(pthread_create(&thread_id[i],NULL,thread_function,¶ms[i]))//创建线程
    handle_error("create thread.");   
  }
      
  for(i=0;i  {
    if(pthread_join(thread_id[i],NULL))
    handle_error("joining thread.");
  }
阅读(918) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~