Chinaunix首页 | 论坛 | 博客

MyL

  • 博客访问: 10182
  • 博文数量: 4
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 50
  • 用 户 组: 普通用户
  • 注册时间: 2010-02-08 14:20
文章分类

全部博文(4)

文章存档

2010年(4)

我的朋友
最近访客

分类: C/C++

2010-07-25 13:59:26


这个是容易出错的代码。不推荐使用:


#include "apue.h"
#include <fcntl.h>
#include <pthread.h>

char buf[]="abcdefghI1234567890";
char nn_read[100];
int fd;


void * thr_fn1(void *arg)
{
    fd=open("./tmp",O_RDONLY);
    lseek(fd,0,SEEK_SET);
    read(fd,nn_read,10);
    close(fd);
    printf("this is thr_fn1:%s\n",nn_read);
}
void * thr_fn2(void *arg)
{
    fd=open("./tmp",O_RDONLY);
    lseek(fd,4,SEEK_SET);
    read(fd,nn_read,10); //lseek和read分开写,在多线程下容易读取出错。。。。
    close(fd);
    printf("this is thr_fn2:%s\n",nn_read);
}




int main(void)
{
    pthread_t tid1,tid2;
    void *tret;
    fd=creat("./tmp",FILE_MODE);
    write(fd,buf,sizeof(buf));


    pthread_create(&tid1,NULL,thr_fn1,NULL);
    pthread_create(&tid2,NULL,thr_fn2,NULL);
    pthread_join(tid1,&tret);
    pthread_join(tid2,&tret);
     exit(0);

}

 

应该使用pread这个原子操作:pread(fd,缓冲区指针,缓冲区大小,偏移量);

 

#include "apue.h"
#include <fcntl.h>
#include <pthread.h>

char buf[]="abcdefghI1234567890";
char nn_read[100];
int fd;


void * thr_fn1(void *arg)
{
    fd=open("./tmp",O_RDONLY);
    //lseek(fd,0,SEEK_SET);
    //read(fd,nn_read,10);
    pread(fd,nn_read,10,0);
    close(fd);
    printf("this is thr_fn1:%s\n",nn_read);
}
void * thr_fn2(void *arg)
{
    fd=open("./tmp",O_RDONLY);
// lseek(fd,4,SEEK_SET);
// read(fd,nn_read,10);
    pread(fd,nn_read,10,4);  // 使用原子操作
    close(fd);
    printf("this is thr_fn2:%s\n",nn_read);
}




int main(void)
{
    pthread_t tid1,tid2;
    void *tret;
    fd=creat("./tmp",FILE_MODE);
    write(fd,buf,sizeof(buf));


    pthread_create(&tid1,NULL,thr_fn1,NULL);
    pthread_create(&tid2,NULL,thr_fn2,NULL);
    pthread_join(tid1,&tret);
    pthread_join(tid2,&tret);
     exit(0);

}


阅读(372) | 评论(0) | 转发(0) |
0

上一篇:unix 编程学习方法

下一篇:没有了

给主人留下些什么吧!~~