Operations on threads in Linux

Source: Internet
Author: User
Operations on threads in Linux
01-7-27 10:39:13 AM

This section describes how to create and use threads in Linux. Threads in Linux are a very complicated issue. Since I have learned a lot about threads from time to time, I am only here to briefly introduce the creation and basic use of threads, for more information about advanced use of threads (such as thread attributes, thread mutex, thread synchronization, and so on), refer to the information I will provide later. Now we can find a lot of English information about threads on the Internet. I will list many links later. If you are interested in the advanced nature of threads, please refer to them. When I have a deep understanding of the thread, I will come back to complete this article. If you have a detailed understanding of the thread, I am very happy to be able to improve it.
First, we will introduce 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 a thread, the program forks where we create a line and becomes two "programs" in execution. It seems like it is similar to a sub-process, but it is not actually. A child process is executed by copying the address space of the parent process. The thread is executed by sharing program code. The common point is that the same code of the thread will be executed several times. The advantage of using threads is that it can save resources. Because threads share code, it is not as complicated as process scheduling.
 
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 is used to indicate the ID of the thread to be created. ATTR indicates the attributes of the thread during creation. We use null to indicate that the default attribute is used. Start_routine function pointer is the function that starts execution after the thread is created successfully. Arg is the only parameter of this function. Indicates the parameter passed to start_routine. The pthread_exit function is similar to the exit function to exit a thread. This function ends the thread, releases the function resource, and blocks it 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 variables of the function. Pthread_join is the same as wait call to wait for the specified thread. Next we will use an instance to explain how to use it. In practice, we often need to back up some files. The following program backs up all files in the current directory. The suffix after 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 [I]-> 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 [I], (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 );
)

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.