Chinaunix首页 | 论坛 | 博客
  • 博客访问: 532713
  • 博文数量: 150
  • 博客积分: 5010
  • 博客等级: 大校
  • 技术积分: 1861
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-17 00:19
文章分类

全部博文(150)

文章存档

2011年(1)

2009年(14)

2008年(135)

我的朋友

分类: LINUX

2008-11-04 17:53:40


在看多线程编程中,一个例子中,我总是得不到理想的结果。两个获取数据的线程得到了数据但是没有经过处理线程的处理。最后看了原作者的程序,才知道pthread_join();用错了,应该让他等待最后退出的线程。

我一开始只是
  pthread_join
(t1,NULL);
   pthread_join(t2,NULL);

没有
 pthread_join(t3,NULL);
   pthread_join(t4,NULL);
这样t1,t2结束后,线程就结束了,t3,t4没来得及开始进程就结束了。
原作者加的了一条注释是: /* 防止程序过早退出,让它在此无限期等待*/
还是作者心细

#include<stdlib.h>
#include<stdio.h>
#include<semaphore.h>
#include<error.h>
#define MAXSIZE 100
int Stack[MAXSIZE][2];
int size=0;
sem_t sem;
void *read_data1(void *arg)
{
    FILE *fp;
    fp=fopen("1.dat","r");
    if(fp==NULL)
    {
     printf("Can not open file \n");
    }
        while(!feof(fp))
    {
     fscanf(fp,"%d %d",&Stack[size][0],&Stack[size][1]);
          printf("In function read_data:Stack[%d]=%d,Stack[%d]=%d\n",size,Stack[size][0],size,Stack[size][1]);
          sem_post(&sem);
          size++;
    }
    fclose(fp);
}
void *read_data2(void *arg)
{
    FILE *fp;
    fp=fopen("2.dat","r");
    if(fp==NULL)
    {
     printf("Can not open file \n");
    }
        while(!feof(fp))
    {
     fscanf(fp,"%d %d",&Stack[size][0],&Stack[size][1]);
          printf("In function read_data:Stack[%d]=%d,Stack[%d]=%d\n",size,Stack[size][0],size,Stack[size][1]);
          sem_post(&sem);
          size++;
    }
    fclose(fp);
}

void *add_thread(void *arg)
{
   while(1)
   {
    sem_wait(&sem);
    printf("Stack[%d](%d)+Stack[%d](%d) = %d\n",size,Stack[size][0],size,Stack[size][1],Stack[size][0]+Stack[size][1]);
        size--;
   }
}
void *multi_thread(void *arg)
{
   while(1)
   { printf("multipler!\n");
    sem_wait(&sem);
    printf("Stack[%d](%d)*Stack[%d](%d) = %d\n",size,Stack[size][0],size,Stack[size][1],Stack[size][0]*Stack[size][1]);
        size--;
   }
}
int main()
{
   pthread_t t1,t2,t3,t4;
   sem_init(&sem,0,0);
   pthread_create(&t1,NULL,read_data1,NULL);
   pthread_create(&t2,NULL,read_data2,NULL);
   //pthread_create(&t3,NULL,add_thread,NULL);

   pthread_create(&t4,NULL,multi_thread,NULL);
   pthread_join(t1,NULL);
   pthread_join(t2,NULL);

  pthread_join(t3,NULL);
   pthread_join(t4,NULL);
   return 0;
}

阅读(1194) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~