Windows system >> Windowsの知識 >  >> Linuxシステムチュートリアル >> Linuxチュートリアル >> Linuxプログラミング入門 - スレッド操作

Linuxプログラミング入門 - スレッド操作

  

コンピューターショップニュースでは最初にスレッドとは何かを紹介していますが、私たちが書くほとんどのプログラムはシングルスレッドと見なすことができます。プログラムは、行を作成した場所で分岐し、実行中の2つの「プログラム」になります。おおまかには子プロセスに似ているようですが、親プロセスのアドレス空間をコピーすることではありません。スレッドはプログラムコードを共有することによって実行されますが、一般的なのは、同じコードが何度も実行されるということですスレッドを使用する利点は、スレッドがコードによって共有されるためリソースを節約できることです。スレッドの作成と使用スレッドの作成は次の関数で行われます:#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はスレッドを作成する、th readは、作成されたスレッドのIDを示すために使用され、attrは、スレッドが作成されたときの属性を示すために、デフォルト属性の使用を示すためにNULLを使用します。この関数は、スレッドを終了し、関数のリソースを解放し、他のスレッドがpthread_join関数を使用して待機するまでブロックを終了した後、* retvalの値を渡します。この関数は関数のリソースを解放するので、retvalは関数のローカル変数を指すことはできませんpthread_joinは指定されたスレッドを待機呼び出しとして待機するために使用されます。次のプログラムでは、現在のディレクトリにあるすべてのファイルをバックアップできますバックアップのサフィックスの名前はbak #include< stdio.h> #include< unistd.h> #include< stdlibです。 h> #include< string.h> #include< errno.h> #include< pthread.h># < 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_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){((bytes_read == - 1)&(errno!= EINTR))break;そうでなければ(bytes_read> 0){buffer_p = buffer; while((bytes_write = write) (outfile、buffer_p、bytes_read))!= 0){((bytes_write == - 1)&&(errno!= EINTR))break;そうでなければ(bytes_write == bytes_read)break;そうでなければ(bytes_write> 0){bu Wr_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ファイル名[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