Linux Multi-threaded learning (1)

Source: Internet
Author: User
Tags terminates

First, write a time-consuming single-threaded program:

#include <cstdio>#include<unistd.h>int  main () {    sleep (5);    printf ("programexited.\n");}

Compile and run the program, which outputs after 5 seconds and no longer responds to other messages or performs other actions during sleep. To better handle this time-consuming operation, we need to use multithreaded programming.

First copy something from the book:

Both processes and threads are concepts of the operating system. A process is an instance of an application that consists of a private virtual address space, code, data, and various other system resources, and the resources created during the process are destroyed as the process terminates, and the system resources used are freed or closed when the process terminates.

A thread is an execution unit within a process. After the system has created a process, the main execution thread that executes the process is actually started, and the main execution thread provides the program's startup point to the operating system in the form of a function address, such as the main function. The primary execution thread terminates, and the process terminates with it.

Each process has at least one master execution thread, which is created automatically by the system without the user being actively created. The user creates additional threads in the application as needed, and multiple threads run concurrently in the same process. All the threads in a process use these virtual address space, global variables and system resources together in the virtual address space of the process, so communication between threads is very convenient, and multithreading technology is widely used.

Multithreading enables parallel processing, avoiding a task that takes up CPU time for a long time. The point is that the current part of the computer is a single processor (CPU), in order to run all these threads, the operating system for each independent thread to schedule some CPU time, the operating system to provide a rotation of the thread time slices, which gives the illusion, as if these threads are running concurrently. This shows that if two very active threads in order to rob the control of the CPU, the thread switching will consume a lot of CPU resources, but will reduce the performance of the system. This should be noted in multithreaded programming.

Programs that have the following characteristics can use threads:

    • Work can be performed concurrently by multiple tasks, or the data can be manipulated by multiple tasks at the same time.
    • Blocking with potential long I/O waits.
    • A lot of CPU cycles are used in some places and nowhere else.
    • Must respond to an asynchronous event.
    • Some work is more important than others (priority interrupts).

Multithreading can also be used in serial programs to simulate parallel execution. A good example is a classic web browser that runs on a single CPU computer, and many things can be "displayed" at the same time.

Several common models that use threading programming:

    • Manager/Worker (Manager/worker): A single thread, as the manager assigns work to other threads (workers), typically, the manager handles all input and assignment work to other tasks. At least two forms of manager/worker models are more commonly used: Static worker pools and dynamic worker pools.

    • Pipeline (Pipeline): A task can be divided into a series of sub-operations, each of which is serially processed and processed concurrently by different threads. The automobile assembly line can describe the model well. such as IDM, such as download software file block at the same time download.

    • Peer: Similar to the Manager/worker model, but the main thread is also involved in the work after it has created other threads.

Next look at the interface Pthread for multithreaded programming.

Thread Management

The first is to create and end threads

function :

int pthread_create (pthread_t *TIDP,const pthread_attr_t *attr, (void*) (*start_ RTN) (void*),void *arg); void pthread_exit (void* retval); int pthread_attr_init (pthread_attr_t *attr); int Pthread_attr_destroy (pthread_attr_t *attr);

To Create a thread :

Initially, the main function contains a default thread. Other threads need to be explicitly created by the programmer. Pthread_create Create a new thread and make it run. This function can be called from anywhere in the program.

Pthread_create parameters and Return values:

The first parameter is a pointer to the thread identifier. cannot be set to NULL.

The second parameter is used to set the thread properties. Can be setNULL为缺省值。

The third parameter is the starting address of the thread's running function, which is线程将会执行一次的C函数。

The last parameter is the argument passed to the run function.传递时必须转换成指向void的指针类型。没有参数传递时,可设置为NULL。

Returns 0 if successful, otherwise the error number is returned.

The maximum number of threads a process can create depends on the system implementation.

Once created, the thread is called peers, and other threads can be created. There is no specified structure and dependency between threads.

There are a couple of questions and answers:

Q: After a thread is created, how do I know when the operating system dispatches the thread to make it run?

A: Unless a thread's scheduling mechanism is used, when and where a thread is executed depends on the implementation of the operating system. Strong programs should not depend on the order in which threads are executed.

In other words, the running result of a multithreaded function may be indeterminate, since it is not known when the system will run the thread.

Thread Properties :

Threads have properties that, in pthread_attr_t, must be initialized before they are processed, and initialized after use. We initialize it with the Pthread_attr_init function, and we use Pthread_attr_destroy to remove the initialization. There are other functions for querying and setting the specified properties of the thread property structure.

The thread property structure is as follows:

typedefstruct{    intEtachstate;//separation State of Threads    intSchedpolicy;//Thread scheduling PolicyStructsched_param Schedparam;//scheduling parameters for threads    intinheritsched;//the inheritance of threads    intScope//Scope of the threadsize_t Guardsize;//Alert buffer size at the end of the thread stack    intStackaddr_set;//stack settings for threads    void* STACKADDR;//the location of the line stackssize_t stacksize;//the size of the line stacks}pthread_attr_t;

After calling Pthread_attr_init, the pthread_t structure contains the default values for all the properties that the operating system implements to support threads.

If you want to remove the initialization of the pthread_attr_t structure, you can call the Pthread_attr_destroy function. If a Property object is allocated dynamic memory space when Pthread_attr_init is implemented, Pthread_attr_destroy also initializes the Property object with an invalid value, so if the pthread_attr_ Destroy removal of the pthread_attr_t structure after initialization is called by the Pthread_create function will cause it to return an error.

Other features and usage of thread properties are discussed later.

End Termination :

There are several ways to end a thread:

    • The thread is returned from the main thread (the initial threads of the main function).
    • The thread called the Pthread_exit function.
    • Other threads use the Pthread_cancel function to end the thread.
    • Call the Exec or Exit function to end the process.

  The pthread_exit is used to explicitly exit the thread. Typically, the Pthread_exit () function exits the thread when it is finished working, or when it is no longer necessary to be called. If the main function exits after calling Pthread_exit (), although there is no executable code in main, the process and all threads remain alive and the other threads will continue to execute. Otherwise, they will terminate with the end of main. For normal exit, you can avoid calling pthread_exit () unless you want a return value. The programmer can optionally specify a terminating state, which is returned to the thread of the connection (join) when any thread joins the thread. The Pthread_exit () function does not close the file, and any open files in the thread will remain open until the threads end.

Now we use multithreading to enable our program to perform other operations during sleep.

#include <cstdio>#include<pthread.h>#include<unistd.h>void* Printhello (void*){     for(intI=1; i<=4; i++) {Sleep (1); printf ("hello!%d sec has past\n", i); }}intMain () {pthread_t tid; Pthread_create (&tid,null,printhello,null); Sleep (5); printf ("Program exited.\n");}

The program uses multi-threading and can output when the main function is sleep.

If we use pthread_exit () to exit in main

#include <cstdio>#include<pthread.h>#include<unistd.h>void* Printhello (void*){     for(intI=1; i<=4; i++) {Sleep (1); printf ("hello!%d sec has past\n", i); }}intMain () {pthread_t tid; Pthread_create (&tid,null,printhello,null);  Pthread_exit (NULL); //to exit main threadprintf"Program exited.\n");//This code will not be executed}

You will find that the child thread can still continue to execute if

    Pthread_exit (NULL);  // to exit main thread

Switch

    return 0;

The program will be terminated directly, not output.

passing parameters to threads

the Pthread_create () function allows the programmer to pass a parameter to the START_RTN function of the thread. When multiple parameters need to be passed, you can break the limit of the number of arguments passed by defining a struct containing all the arguments to pass, and then passing a pointer to the struct with pthread_create (). All parameters should be passed by reference and converted into (void*).

  要安全地向一个新创建的线程传递数据应确保所传递的数据是线程安全的(不能被其他线程修改)。

The following code snippet demonstrates how to pass a simple integer to a thread.

#include <cstdio>#include<pthread.h>#include<unistd.h>void* Printid (void* id) {    printf ("my thread id is%d\n", * (int*) ID) ;} int Main () {    pthread_t tid;    Pthread_create (&tid,null,printid, (void*) tid);    Pthread_exit (NULL); // do not use return because the main function exits too quickly so that the child threads are terminated without output }

  The following code snippet demonstrates how to pass a struct-body parameter to a thread.

#include <cstdio>#include<pthread.h>#include<unistd.h>structpoint{intx, y;};void* Print (void*p) {printf ("I got a point (%d,%d). \ n", ((point*) p)->x, ((point*) p),y);}intMain () {pthread_t tid[Ten]; Point p[Ten];  for(intI=0;i<Ten; i++) {p[i].x=p[i].y=i; Pthread_create (&tid[i],null,print, (void*) &P[i]); } pthread_exit (NULL);}

While the following code is wrong, the loop will change the address passed to the thread before it accesses the passed parameters, which will result in a fragment error (segmentation fault).

#include <cstdio>#include<pthread.h>#include<unistd.h>void* Printid (void*i) {printf ("I got a number%d\n",*(int*) i);}intMain () {pthread_t tid[Ten];  for(intI=0;i<Ten; i++) {pthread_create (&tid[i],null,printid, (void*) (i); } pthread_exit (NULL);}

Linux Multi-threaded learning (1)

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.