Windows XP Windows 7 Windows 2003 Windows Vista Windows教程綜合 Linux 系統教程
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟件教程
 Windows教程網 >> Linux系統教程 >> Linux教程 >> Linux程序設計入門--線程操作

Linux程序設計入門--線程操作

日期:2017/2/7 9:19:49      編輯:Linux教程

   電腦店訊   先介紹什麼是線程.我們編寫的程序大多數可以看成是單線程的.就是程序是按照一定的順序來執行.如果我們使用線程的話,程序就會在我們創建線成的地方分叉,變成兩個"程序"在執行.粗略的看來好象和子進程差不多的,其實不然.子進程是通過拷貝父進程的地址空間來執行的.而線程是通過共享程序代碼來執行的,講的通俗一點就是線程的相同的代碼會被執行幾次.使用線程的好處是可以節省資源,由於線程是通過共享代碼的,所以沒有進程調度那麼復雜.
線程的創建和使用
線程的創建是用下面的幾個函數來實現的.
#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的參數. pthrea
d_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)
{
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)

Copyright © Windows教程網 All Rights Reserved