C + + Multithreading 0

Source: Internet
Author: User

1.1 What is concurrency

The simplest and most basic concurrency refers to the simultaneous occurrence of two or more independent activities. (Note that it differs from the concurrency situation in the computer!!!!!!!!!! See below)

1.1.1 concurrency in a computer system: It is the execution of multiple independent tasks in a single systems, rather than sequential activities .

Doing this task for a while, switching to another task, and then doing it for a while, makes the task appear to be executed in parallel, which is called "task switching" and is now still called concurrency.

You should switch the task too fast to feel that the task is suspended when it is not. Task switching creates a " Concurrency Illusion " for the user. Because of this illusion, when applied in the context of task switching and the real

There is a subtle difference in behavior compared to executing in a concurrent environment. In particular, assumptions about the incorrect memory model may not occur in a multithreaded environment.

Figure 1.1 shows the ideal scenario for a computer to handle two tasks, each divided into 10 equal-sized blocks.                  On a dual-core machine, each task can be executed on its own processing. When a task is switched on a single-core machine, the block of each task is interleaved. But there is a small section in the middle; To achieve interleaving, each time you switch from one task to another, you need to swap the context and switch to a time overhead .           When switching, the operating system must save the state of the CPU and the instruction pointer for the currently running task , calculate which task to switch to, and reload the processor state for the task that is about to switch to. TheCPU may then load the memory of the new task's instructions and data into the cache, which prevents the CPU from executing any instructions, resulting in more delays .

Figure 1.1 Concurrency in two ways: true parallel Vs. Single-core machine task switching

Figure 1.2 Four tasks switching between two cores

Figure 1.3 Communication between a pair of concurrently running processes

Figure 1.4 Communication between a pair of concurrently running threads in the same process

Listing 1.1 A simple Hello, Concurrent World program:

#include <iostream>#include <thread> //①void hello() //②{ std::cout << "Hello Concurrent World\n";}int main(){ std::thread t(hello); //③ t.join(); //④}

④ is called here join() because this causes the calling thread (in main () to wait for the std::thread thread associated with the object , that is, t in this example.

2nd Chapter Thread Management

Main content

    • Start a new thread
    • Waiting for thread to detach thread
    • Thread Unique identifier

2.1.1 Start thread

1 in the simplest case, the task will be simple, usually a function without parameters and no return (void-returning) . This function runs on the thread it belongs to, until the function is finished and the thread ends.

void do_some_work();std::thread my_thread(do_some_work);

2 Pass an instance with a function-call type into the std::thread class, replacing the default constructor.

 class background_task{ public: operator()() const{ //这个类型重载了运算符() do_something(); do_something_else(); } };background_task f;std::thread my_thread(f);

Attention:

When you pass a function object into the thread constructor, you need to avoid the "most troublesome parsing of syntax" (C + + 's most vexing parse, Chinese profile).

If you pass a temporary variable instead of a named variable, the C + + compiler resolves it to a function declaration instead of the definition of the type object.

For example:

std::thread my_thread( background_task() );

In this case, a function named My_thread is declared , which takes a parameter (the function pointer points to a function that has no arguments and returns the Background_task object), and returns a std::thread function of an object. rather than starting a thread .

lambda Expressions can also avoid this problem by using the way in which the function objects are named earlier, or by using multiple sets of parentheses ①, or by using the new unified initialization syntax ②.

As shown below:

std::thread my_thread( ( background_task()) ); // 1std::thread my_thread{ background_task() }; // 2

==============================================================

启动了线程,你需要明确是要等待线程结束(join),还是让其自主运行(detach分离式)。

如果std::thread对象销毁之前还没有做出决定,程序就会终止(std::thread的析构函数会调用std::terminate())。

因此,即便是有异常存在,也需要确保线程能够正确的加入(joined)或分离(detached)。

C + + Multithreading 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.