linux线程通信机制,linux线程之通信机制

一 进程和线程异同点

相同点:

(1)都有ID标识

(2)统一调度

(3)Linux 描述都是用task_struct

(5)都使用父进程的资源

(6)都有一组寄存器的值

不同点:

(1)进程间独立地址空间,多个线程共享同一个进程的地址空间

进程优点安全性高,缺点开销大

线程优点开销小,效率高,缺点安全性差

二 线程

A.创建

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,

void *(*start_routine) (void *), void *arg);

功能:创建线程

参数一:获得线程ID

参数二:指定线程的属性,默认为NULL

参数三 :指定线程的执行函数,线程函数必须是返回值void *,并且含有一个void *参数

参数四 :给线程函数传递参数的

返回值:成功返回0,失败返回错误码

B.线程退出

int pthread_exit(void *addr);

C.等待线程退出

pthread_join(pthread_t tid,void **value);

特点:如果指定的线程没有结束,它会引起调用着阻塞

练习:

1.以都写方式打开一个文件,文件不存在则创建,文件存在清空

2.创建两个线程(read_thread,write_thread),将获得fd作为参数传递

3.read_thread从文件读取数据,打印,写线程向文件中写数据,写入的内容从键盘输入

如果输入"quit",结束线程

4.在主线程中等待这两个线程退出

#include #include #include #include #include #include #include #include

int flag = 0;

void *read_thread(void *arg)

{

int n;

char buf[1024];

int fd = *((int *)arg);

int last_offset = 0;

while(1)

{

while(!flag);

lseek(fd,last_offset,SEEK_SET);

n = read(fd,buf,sizeof(buf) - 1);

buf[n]  = '\0';

printf("Read %d bytes : %s.\n",n,buf);

if(strncmp(buf,"quit",4) == 0)

break;

flag = 0;

last_offset = lseek(fd,0,SEEK_CUR);

}

pthread_exit(NULL);

}

void *write_thread(void *arg)

{

char buf[1024];

int fd = *((int *)arg);

while(1)

{

fgets(buf,sizeof(buf),stdin);

buf[strlen(buf) - 1] = '\0';

write(fd,buf,strlen(buf));

flag = 1;

if(strncmp(buf,"quit",4) == 0)

break;

}

pthread_exit(NULL);

}

//./a.out file

int main(int argc, const char *argv[])

{

int ret;

int fd;

pthread_t tid[2];

if(argc < 2)

{

fprintf(stderr,"Usage : %s argv[1].\n",argv[0]);

exit(EXIT_FAILURE);

}

if((fd = open(argv[1],O_RDWR | O_CREAT | O_TRUNC,0666)) < 0)

{

fprintf(stderr,"Fail to open %s : %s.\n",argv[1],strerror(errno));

exit(EXIT_FAILURE);

}

ret = pthread_create(&tid[0],NULL,read_thread,(void *)&fd);

if(ret != 0){

perror("Fail to pthread_create");

exit(EXIT_FAILURE);

}

ret = pthread_create(&tid[1],NULL,write_thread,(void *)&fd);

if(ret != 0){

perror("Fail to pthread_create");

exit(EXIT_FAILURE);

}

pthread_join(tid[0],NULL);

pthread_join(tid[1],NULL);

exit(EXIT_SUCCESS);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值