Linux programming basics-thread Overview

Source: Internet
Author: User

Sometimes, we need to run multiple control flows simultaneously in one infrastructure. For example, a graphical download software must respond to control operations such as stopping and deleting a task while processing the download task. In this case, threads are required to implement concurrent operations.

Unlike the control of signal processing functions, the control process of multiple threads can coexist for a long time, and the operating system schedules and switches between threads, just like scheduling and switching between multiple processes, the thread creation overhead is much lower than the process. Therefore, threads are often called Lightweight processes.

Because multiple threads of the same process share the same address space, data segments are shared. If a global variable is defined, it can be accessed in each thread. However, some resources still have a copy of each thread:

  • Thread id
  • Context, including the values of various registers, program counters, and stack pointers
  • Stack space
  • Errno variable
  • Signal shielding characters
  • Scheduling Priority

We generally use a thread library function defined by the POSIX standard, called POSIX thread or pthread. In Linux, the thread function is located in the libpthread shared library. Therefore, the-lpthread option must be added during compilation.

Create thread

In the POSIX library, the creation thread is implemented through functions. Its declaration is as follows:

# Include <pthread. h>

Int pthread_create (pthread_t * thread, const pthread_attr_t * attr,

Void * (* start_routine) (void *), void * arg );

It has four parameters,

  • The first parameter thread is the pointer to the created thread identifier.
  • The second parameter attr is the thread attribute, which can be PTHREAD_CREATE_DETACHED (separated thread) and PTHREAD _ CREATE_JOINABLE (non-separated thread). Generally, NULL is used directly.
  • The third parameter start_routine is the running function of the thread.
  • The fourth parameter arg is the parameter of the thread-running function.
  • 0 is returned when creation is successful. If creation fails, an error code is returned. The error code returned by errno is not the same as that returned by other system functions.

A simple example is as follows:

# Include <stdio. h>
# Include
<String. h>
# Include
<Stdlib. h>
# Include
<Pthread. h>
# Include
<Unistd. h>

Void * thr_fn (void * arg)
{
Pid_t pid = getpid ();
Pthread_t tid = pthread_self ();

Printf ("% s pid % u tid % u (0x % x) \ n", arg, (unsigned
Int) pid, (unsigned
Int) tid, (unsigned
Int) tid );

Return NULL;
}

Int main (void)
{
Pthread_t ntid = {0 };

Int err = pthread_create (& ntid, NULL, thr_fn, (void *) "new thread :");
If (err! = 0)
{
Fprintf (stderr, "can't create thread: % s \ n", strerror (err ));
Exit (1 );
}

Void * tret;
Pthread_join (ntid, & tret );
Printf ("thread exited \ n ");

Return 0;
}

When we compile this program, we will find the following error:

Tianfang @ linux-k36c:/mnt/share/test> make
Make: Warning: File 'makefile' has modification time 0.48 s in the future
G ++-o run main. o
Main. o: In function 'main ':
/Mnt/share/test/main. cpp: 20: undefined reference to 'pthread _ create'
Collect2: error: ld returned 1 exit status
Make: *** [run] Error 1
Tianfang @ linux-k36c:/mnt/share/test>

This is a link error. It means that the pthread_create function definition cannot be found. This is because the thread function in Linux is located in the libpthread shared library, so the-lpthread option must be added during compilation.

Wait until the thread ends

Sometimes, we need to wait until the thread ends before continuing to execute the following tasks. Taking the preceding example as an example, if the main thread (main function) is directly executed without waiting for the end of the thread, causing the program to exit and the thread functions cannot be executed.

In the pthread library, the function waiting for the end of the thread is pthread_join. Its declaration is as follows:

# Include
<Pthread. h>
Int pthread_join (pthread_t thread, void ** retval );

It has two parameters. The first parameter is the thread identifier, and the second parameter is an output parameter. The user obtains the return value of the thread function. Pthread_join has been demonstrated in the previous example, so we will not introduce it here.

Terminate thread

Generally, there are several methods to terminate a thread:

  • The thread function calls return to terminate itself.
  • The thread calls pthread_exit to terminate itself.
  • The thread can call pthread_cancel to terminate other threads in the same process.

Methods 1 and 2 actively exit by ending the thread function. They are commonly used. Method 3 is a forced termination method. A problem with this method is that the object's destructor may fail to be executed, causing resource leakage. This method is not recommended.

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.