岁月联盟 · 中国技术网 本站主页 | 安全认证 | 用户服务 | 技术论坛
新闻快报 | 新手学堂 | 黑客特区 | 程序语言 | 数 据 库 | 防 火 墙 | 路由交换 | 系统集成 | 服 务 器 | 存储备份 | 考试认证
Windows | Linux | Java | 协议分析 | 问题解答 | 进程大全 | 网页设计 | 多 媒 体 | 图库资料 | 软件下载 | 站内下载
  您现在的位置: 岁月联盟 >> Linux频道 >> Linux编程 >> CC编程 >> Linux频道正文
linux操作系统下c语言编程入门--线程操作
作者:未知 文章来源:本站整理 点击数: 更新时间:2007-12-18 18:13:52

        线程的创建和使用

        线程的创建是用下面的几个函数来实现的.

        #include <pthread.h>
        int pthread_create(pthread_t *thread,pthread_attr_t *attr,
        void *(*start_routine)(void *),void *arg);
        void pthread_exit(void *retval);
        int pthread_join(pthread *thread,void **thread_return);

        pthread_create创建一个线程,thread是用来表明创建线程的ID,attr指出线程创建时候的属性,我们用NULL来表明使用缺省属性.start_routine函数指针是线程创建成功后开始执行的函数,arg是这个函数的唯一一个参数.表明传递给start_routine的参数. pthread_exit函数和exit函数类似用来退出线程.这个函数结束线程,释放函数的资源,并在最后阻塞,直到其他线程使用pthread_join函数等待它.然后将*retval的值传递给**thread_return.由于这个函数释放所以的函数资源,所以retval不能够指向函数的局部变量. pthread_join和wait调用一样用来等待指定的线程. 下面我们使用一个实例来解释一下使用方法.在实践中,我们经常要备份一些文件.下面这个程序可以实现当前目录下的所有文件备份.备份后的后缀名为bak

        #include <stdio.h>
        #include <unistd.h>
        #include <stdlib.h>
        #include <string.h>
        #include <errno.h>
        #include <pthread.h>
        #include <dirent.h>
        #include <fcntl.h>
        #include <sys/types.h>
        #include <sys/stat.h>
        #include <sys/time.h>
        #define BUFFER 512
        struct copy_file {
        int infile;
        int outfile;
        };
        void *copy(void *arg)
        {
        int infile,outfile;
        int bytes_read,bytes_write,*bytes_copy_p;
        char buffer[BUFFER],*buffer_p;
        struct copy_file *file=(struct copy_file *)arg;
        infile=file->infile;
        outfile=file->outfile;
        /* 因为线程退出时,所有的变量空间都要被释放,所以我们只好自己分配内存了 */
        if((bytes_copy_p=(int *)malloc(sizeof(int)))==NULL) pthread_exit(NULL);
        bytes_read=bytes_write=0;
        *bytes_copy_p=0;
        /* 还记得怎么拷贝文件吗 */
        while((bytes_read=read(infile,buffer,BUFFER))!=0)
        {
        if((bytes_read==-1)&&(errno!=EINTR))break;
        else if(bytes_read>0)
      &nb

[1] [2] [3] 下一页


  • 上一个Linux频道:
  • 下一个Linux频道:
  •  
    热门文章
    推荐文章
    关于我们 | 发展历程 | 网站地图 | 广告服务 | 招贤纳士 | 战略合作 | 友情链接 | 著作声明 | 联系我们
    Copyright © 2002-2007 SYUE All rights reserved.
    E_mail:Admin@Syue.Com 皖ICP备05004589号
    未经授权禁止转载、摘编、复制或建立镜像.如有违反,追究法律责任.
    天龙八部私服 传世私服 传奇世界私服 传奇私服 bet365 天龙八部私服 热血江湖私服 英雄合击传奇私服 热血江湖私服 bet365 bet365