Introduction to Linux program design-thread operations

Source: Internet
Author: User
Introduction to Linux programming-thread operations-general Linux technology-Linux programming and kernel information. For details, see the following. Thread creation in Linux
This article describes how to create and use threads in Linux. threads in Linux are a very complicated problem.
It is good for me to learn about threads from time to time. Here I am just a brief introduction to thread creation and basic usage.
For more information about advanced use of a thread (such as thread attributes, thread mutex, thread synchronization, and so on), refer to
Materials. Now we can find a lot of English information about threads on the Internet. I will list many links later.
For more information about the advanced thread, see. When I have a deep understanding of the thread, I will come back.
This article is completed. If you have a detailed understanding of the thread, I am very happy to be able to improve it.
First, we will introduce what is thread. Most of the programs we write can be regarded as single-threaded.
It is executed in sequence. If we use a thread, the program forks at the place where we create the line and turns it into two "Processes
In execution, the sub-process is roughly the same as the sub-process. In fact, the sub-process is copied to the parent process.
The thread is executed by sharing program code. The common point is that the thread is the same.
The code will be executed several times. The advantage of using the thread is that it can save resources. Because the thread shares the code, no
Process Scheduling is complicated.
Creation and use of threads
The following functions are used to create threads.
# Include ;
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 creates a thread. thread indicates the ID of the thread to be created. attr indicates the thread creation time.
The default property. start_routine function pointer is used after the thread is created successfully.
The execution function. arg is the only parameter of this function. It indicates the parameter passed to start_routine. pthrea
The d_exit function is similar to the exit function to exit the thread. This function ends the thread, releases the function resources, and
Blocking until other threads use the pthread_join function to wait for it. Then pass the * retval value to ** thread _
Return. Because this function releases function resources, retval cannot point to the local variable. pt of the function.
Hread_join is the same as wait call to wait for the specified thread. Here we use an instance to explain how
In practice, we often need to back up some files. The following program can implement all the files in the current directory
Backup. The suffix after the backup is bak
# Include ;
# Include ;
# Include ;
# Include ;
# Include ;
# Include ;
# Include ;
# Include ;
# Include ;
# Include ;
# Include ;
# 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;
/* Because all the variable space will be released when the thread exits, We have to allocate the memory by ourselves */
If (bytes_copy_p = (int *) malloc (sizeof (int) = NULL) pthread_exit (NULL );
Bytes_read = bytes_write = 0;
* Bytes_copy_p = 0;
/* Do you still remember how to copy the object */
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;
/* Obtain the number of all files (including directories) in the current path */
If (num = scandir (".", & namelist, 0, alphasort) <0)
{
Fprintf (stderr, "Get File Num Error: % s \ n \ a", strerror (errno ));
Exit (1 );
}
/* Allocate space to the thread. In fact, there is no need to allocate so much space */
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 \ ");
Exit (1 );
}

For (I = 0, j = 0; I {
Memset (filename, '\ 0', BUFFER );
Strcpy (filename, namelist->; d_name );
If (stat (filename, & filestat) =-1)
{
Fprintf (stderr, "Get File Information: % s \ n \ a", strerror (errno ));
Exit (1 );
}
/* We ignore the directory */
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 {
/* Wait for the thread to end */
If (pthread_join (thread, (void **) & byte_copy_p )! = 0)
Fprintf (stderr, "Thread [% d] Join Error: % s \ n \ ",
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 in the copy function */
Free (byte_copy_p );
}
}
Printf ("Total Copy Bytes % d \ n \ a", byte_copy );
Free (thread );
Free (file );
Exit (0 );
}
This is the thread introduction. For more information about the thread, see the following link.
Getting Started With POSIX Threads
The LinuxThreads library
Related Article

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.