8) Introduction to Linux programming--Threading operations

Source: Internet
Author: User

8) Introduction to Linux programming--Threading Operations Preface: The creation of Linux thread is introduced in the creation and basic use of Linux thread. Linux thread is a very complex problem, because I am learning about threading is very good, I am here to simply introduce the creation of threads and basic use, about the advanced use of threads (such as thread properties, thread mutual exclusion, thread synchronization, etc.) can refer to the information I gave later. Now about the thread of information on the network can find a lot of English material, I listed a lot of links, I am interested in the advanced properties of threads can refer to. By the time I learned more about threads, I came back to finish this article. If you know more about threading I'm very happy to be able to improve it. Let's start by describing what a thread is. Most of the programs we write can be considered single-threaded. That is, the program is executed in a certain order. If we use threads, the program will fork in the place where we created the line, turning into two"ProcessOrder"in execution. Rough looks like a sub-process, not really. A child process is copied by copying the parent processaddress space. While threads are executed by sharing program code, the common point is that the same code of the thread is executed several times. The advantage of using threading is that it saves resources because threads are shared code, so no process scheduling is as complex. Thread creation and use The creation of threads is implemented using several functions below. #include<pthread.h>; intPthread_create (pthread_t *thread,pthread_attr_t *attr,void* (*start_routine) (void*),void*Arg); voidPthread_exit (void*retval); intPthread_join (Pthread *thread,void**Thread_return); Pthread_create creates a thread, which is used to indicate that the id,attr that created the thread is the attribute at the time of creation, and we use NULL to indicate that the default property is used. The Start_routine function pointer is a function that starts executing after the thread is created successfully. Arg is the only argument to this function. Indicates the arguments passed to the start_routine. The Pthrea d_exit function and the Exit function are similar to exiting a thread. This function ends the thread, frees the function's resources, and then blocks until the other thread waits for it using the Pthread_join function. ThenThe value of the *retval is passed to * *Thread_returnbecause this function frees the function resources, retval cannot point to the local variables of the function. The PT hread_join and the wait call are used just as long to wait for the specified thread. Here we use an example to explain how to use it. In practice, We often have to back up some files. The following program can be used to implement all file backups in the current directory. The suffix named bak after backup #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>; #defineBUFFER 512structCopy_file {intinfile;intoutfile;}; void*copy (void*Arg) { intInfile,outfile;intbytes_read,bytes_write,*bytes_copy_p;Charbuffer[buffer],*buffer_p;structCopy_file *file= (structCopy_file *) Arg; InFile=file->; infile; outfile.=file->; outfile;/*since the thread exits, all the variable spaces are freed, so we have to allocate our own memory.*/ if((Bytes_copy_p= (int*) malloc (sizeof(int)))==null) pthread_exit (NULL); Bytes_read=bytes_write=0; *bytes_copy_p=0; /*Do you remember how to copy files?*/  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); } intMainintargcChar**argv) {pthread_t*thread;structCopy_file *file;intbyte_copy,*byte_copy_p,num,i,j;CharFilename[buffer];structDirent * *NameList;structstat Filestat;/*get the number of all files (including directories) below the current path*/ if((Num=scandir (".", &namelist,0, Alphasort)) <0) {fprintf (stderr,"Get File Num error:%s\n\a", Strerror (errno)); Exit (1); } /*assigning space to a thread is actually not necessary so much*/ if((thread= (pthread_t *) malloc (sizeof(pthread_t) *num)) ==null) | |(File=(structCopy_file *) malloc (sizeof(structCopy_file) (*num)) = =NULL)) {fprintf (stderr,"Out of memory!\n\a"); Exit (1); }   for(i=0, j=0; i<num;i++) {memset (filename,' /', BUFFER); strcpy (Filename,namelist-;d _name); if(Stat (FILENAME,&AMP;FILESTAT) ==-1) {fprintf (stderr,"Get File information:%s\n\a", Strerror (errno)); Exit (1); } /*We ignore the catalog*/ 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; } /*create a thread to copy files*/ 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++) { /*wait for thread to end*/ if(Thread, (Pthread_join) (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;/*Release the memory we created inside the copy function*/Free (byte_copy_p); }} printf ("Total Copy Bytes%d\n\a", byte_copy); Free (thread); Free (file); Exit (0); The description of the thread is here, and other information about the thread can be viewed in the following link. Getting Started with POSIX Threads the linuxthreads library [size= -][color=red]< to Be Continued >; [/color] [/size] 007xiong reply to:2003-Geneva- - Geneva: One: $[Size= -][color=red] continued pre-paste [/color][/size]

8) Introduction to Linux programming--Threading operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.