Linux Multithreading (i) (Create and exit)

Source: Internet
Author: User
Tags cpu usage

1. Linux Multithreading Overview 1.1. Overview

Process is the basic unit of program execution and resource allocation in the system. Each process has its own data segments, code snippets, and stack segments. This causes the process to switch operations such as a more responsible context switch and other actions. Threads are also present in order to further reduce processor idle time to support multiprocessor and reduce context switching overhead.

Threads are often called lightweight processes. A thread is a multi-channel execution path that executes concurrently in a shared memory space, is a concept that is closer to the execution body, has a separate execution sequence, is the basic dispatch unit of the process, and each process has at least one main thread. It shares the process space {heap Code data file descriptor signal, etc.} with other threads in the process, and only has its own stack space, greatly reducing the overhead of context switching.

Threads and processes have advantages and disadvantages in use: small thread execution overhead, low CPU usage, fast switching between threads, but not conducive to resource management and protection, while the process is the opposite. In terms of portability, the portability of multiple processes is better.

As with the process, the thread also puts the associated variable values inside the inline control table. A process can have multiple threads, that is, multiple thread control tables and stack registers, but share a user address space. It is important to note that because threads share the resources and address space of a process, any thread's operations on system resources can affect other threads.

1.2. Thread classification

Divided by dispatcher into user-level threads and core-level threads

• User-level threading: The main solution to the context switching problem, the scheduling algorithm and scheduling process are all determined by the user, at run time does not require specific kernel support. Disadvantage is the inability to leverage the benefits of multiprocessor

• Core-level threading: Allows threads in different processes to schedule with the same relative-priority scheduling method, giving them the concurrency benefits of multiprocessor

Most systems now employ both user-level threads and core-level threading methods. A user-level thread can correspond to one or more core-level threads, that is, a single or one-to-many model.

1.3. Thread-created Linux implementations

Linux threads are implemented through a user-level library of functions, generally using pthread-line libraries to achieve thread access and control. It uses the 3rd party POSIX standard Pthread, which has good portability. When compiling, add –lpthread to the back.

Create Exit wait

Multi-process fork () exit () Wait ()

Multithreading Pthread_create Pthread_exit () Pthread_join ()

2. Creation and exit of threads

Creating a thread is essentially determining the entry point to invoke the thread function, and the thread is created using the function pthread_create. After the thread has been created, the associated threading function starts running, and the thread exits when the function finishes running, which is also a way for the thread to exit. Another way to exit a thread is to use the function pthread_exit () function, which is the thread's active exit behavior. It is important to note that when you use the thread function, you cannot use the exit Exit function for error handling, because exit is used to terminate the calling process, often a process consists of multiple threads, so the pthread_exit function is usually substituted for exit functions in the process.

Because more than one thread in a process is a shared data segment, the resources that are consumed by the exit thread will not be freed as the thread terminates after threads are usually exited. Just as processes can be called by the Wait () function system to terminate and release resources synchronously, there is a similar mechanism between threads, which is the Pthread_join function. The Pthread_join function can be used to suspend the current thread, waiting for the end of the thread. This function is a thread-blocking function, and the function that invokes it waits until the thread that is waiting ends, and when the function returns, the resource that is waiting for the thread is recycled.

Function Prototypes:

#include <pthread.h>

int pthread_create (pthread_t* thread, pthread_attr_t * attr, void * (*start_routine) (void *), void * arg);

void Pthread_exit (void *retval);

The usual form is:

pthread_t Pthid;

Pthread_create (&pthid,null,pthfunc,null), or Pthread_create (&pthid,null,pthfunc, (void*) 3);

Pthread_exit (NULL), or Pthread_exit ((void*) 3),//3 as the return value is captured by the Pthread_join function.

The function pthread_create is used to create threads. Return value: Success, 0 is returned, or 1 if failed. The parameters are described as follows:

• The parameter thread is an outgoing parameter that holds the identity of the new thread;

• Parameter attr is a struct pointer, the elements in the structure specify the running properties of the new thread, attr can set the values of each member with functions such as pthread_attr_init, but it is usually passed to null;

• Parameter start_routine is a function pointer that points to the entry point function of the new thread, and the thread entry point function with a void * parameter is passed in by the 4th parameter of Pthread_create;

• Parameter arg is used to pass arguments to the entry point function that the 3rd parameter points to, which can be null, which means no delivery.

The function Pthread_exit represents the exit of the thread. Its parameters can be captured by other threads using the Pthread_join function.

Example:

#include <stdio.h>

#include <pthread.h>

void *threadfunc (void *parg)//parameter has a value of 123

{

int i = 0;

for (; i<10; i++)

{

printf ("Hi,i ' m child Thread,arg is:%d\n", (int) parg);

Sleep (1);

}

Pthread_exit (NULL);

}

int main ()

{

pthread_t Thdid;

Pthread_create (&thdid, NULL, ThreadFunc, (void *) 123);

int i = 0;

for (; i<10; i++)

{

printf ("Hi,i ' m main thread,child thread ID is:%x\n", thdid);

Sleep (1);

}

return 0;

}

The compile-time libraries option is required with the on line:

Gcc-o a A.c-lpthread

Linux Multithreading (i) (Create and exit)

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.