Linux系统编程6.线程操作

编写的程序大多数可以看成是单线程的.就是程序是按照一定的顺序来执行.如果我们使用线程的话,程序就会在我们创建线成的地方分叉,变成两个”程序”在执行.粗略的看来好象和子进程差不多的,其实不然.子进程是通过拷贝父进程的地址空间来执行的.而线程是通过共享程序代码来执行的,讲的通俗一点就是线程的相同的代码会被执行几次.使用线程的好处是可以节省资源,由于线程是通过共享代码的,所以没有进程调度那么复杂。

1. 线程创建

#include <pthread.h>;
int pthread_create(pthread_t *thread,pthread_attr_t *attr,
void *(*start_routine)(void *),void *arg);
/*
    创建一个线程.
    thread 是用来表明创建线程的 ID,
    attr 指出线程创建时候的属性,用 NULL 来表明使用缺省性.
    start_routine 函数指针是线程创建成功后开始执行的函数.
    arg 是这个函数的唯一一个参数.表明传递给 start_routine 的参数. 
*/

void pthread_exit(void *retval);
/*
    pthread_exit 函数和 exit 函数类似用来退出线程.
    这个函数结束线程,释放函数的资源,并在最后阻塞,直到其他线程使用 
*/
int pthread_join(pthread *thread,void **thread_return);
/*
    pthread_join 函数等待它.然后将*retval 的值传递给**thread_
return.
    由于这个函数释放所有的函数资源,所以 retval 不能够指向函数的局部变量. 
    pthread_join 和 wait 调用一样用来等待指定的线程. 
*/
#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)
        {
            buffer_p=buffer;
            while((bytes_write=write(outfile,buffer_p
    ,bytes_read))!=0)
            {
                if((bytes_write==-1)&&(errno!=EINTR))
                    break;
                else if(bytes_write==bytes_read)
                    break;
                else if(bytes_write>0)
                {
                    buffer_p+=bytes_write;
                    bytes_read-=bytes_write;
                }
            }
            if(bytes_write==-1)
                break;
            *bytes_copy_p+=bytes_read;
        }
    }
    close(infile);
    close(outfile);
    pthread_exit(bytes_copy_p);
}
int main(int argc,char **argv)
{
    pthread_t *thread;
    struct copy_file *file;
    int byte_copy,*byte_copy_p,num,i,j;
    char filename[BUFFER];
    struct dirent **namelist;
    struct stat filestat;

    /* 得到当前路径下面所有的文件(包含目录)的个数 */
    if((num=scandir(".",&namelist,0,alphasort))<0)
    {
        fprintf(stderr,"Get File Num Error: %s\n\a",strerror(errno));
        exit(1);
    }
    /* 给线程分配空间,其实没有必要这么多的 */
    if(((thread=(pthread_t*)malloc(sizeof(pthread_t)*num))==NULL)||((file=(struct copy_file *)malloc(sizeof(struct copy_file)*num))==NULL)
)
    {
        fprintf(stderr,"Out Of Memory!\n\a");
        exit(1);
    }
    for(i=0,j=0;i<num;i++)
    {
        memset(filename,'\0',BUFFER);
        strcpy(filename,namelist[i]->d_name);
        if(stat(filename,&filestat)==-1)
        {
            fprintf(stderr,"Get File Information: %s\n\a",strerror(errno));
            exit(1);
        }
/* 我们忽略目录 */
        if(!S_ISREG(filestat.st_mode))
            continue;

        if((file[j].infile=open(filename,O_RDONLY))<0)
        {
            fprintf(stderr,"Open %s Error: %s\n\a",filename,strerror(errno));
            continue;
        }
        strcat(filename,".bak");
        if((file[j].outfile=open(filename,O_WRONLY|
        O_CREAT,S_IRUSR|S_IWUSR))<0)
        {
            fprintf(stderr,"Creat %s Error: %s\n\a",filename,strerror(errno));
            continue;
        }
        /* 创建线程,进行文件拷贝 */
        if(pthread_create(&thread[j],NULL,copy,(void *)&file[j])!=0)
        fprintf(stderr,"Create Thread[%d] Error: %s\n\a",i,strerror(errno));
        j++;
    }
    byte_copy=0;
    for(i=0;i<j;i++)
    {
        /* 等待线程结束 */
        if(pthread_join(thread,(void **)&byte_copy_p)!=0)
        fprintf(stderr,"Thread[%d] Join Error: %s\n\a",
        i,strerror(errno));
        else
        {
            if(bytes_copy_p==NULL)continue;
            printf("Thread[%d] Copy %d bytes\n\a",i,*byte_copy_p);
            byte_copy+=*byte_copy_p;
            /* 释放我们在 copy 函数里面创建的内存 */
            free(byte_copy_p);
        }
    }
    printf("Total Copy Bytes %d\n\a",byte_copy);
    free(thread);
    free(file);
    exit(0);
}

编译时使用 -lpthread 连接pthread库

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章