Главная » Просмотр файлов » B. Stroustrup - The C++ Programming Language

B. Stroustrup - The C++ Programming Language (794319), страница 30

Файл №794319 B. Stroustrup - The C++ Programming Language (B. Stroustrup - The C++ Programming Language) 30 страницаB. Stroustrup - The C++ Programming Language (794319) страница 302019-05-09СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 30)

For a given application domain, a huge commercial library cancome close to that ideal. However, that is not what the C++ standard library is trying to do. Amanageable, universally available, library cannot be everything to everybody. Instead, the C++standard library aims to provide components that are useful to most people in most applicationareas. That is, it aims to serve the intersection of all needs rather than their union.

In addition, support for a few widely important application areas, such as mathematical computation and textmanipulation, have crept in.112A Tour of C++: Concurrency and UtilitiesChapter 55.2 Resource ManagementOne of the key tasks of any nontrivial program is to manage resources. A resource is somethingthat must be acquired and later (explicitly or implicitly) released. Examples are memory, locks,sockets, thread handles, and file handles. For a long-running program, failing to release a resourcein a timely manner (‘‘a leak’’) can cause serious performance degradation and possibly even a miserable crash.

Even for short programs, a leak can become an embarrassment, say by a resourceshortage increasing the run time by orders of magnitude.The standard library components are designed not to leak resources. To do this, they rely on thebasic language support for resource management using constructor/destructor pairs to ensure that aresource doesn’t outlive an object responsible for it. The use of a constructor/destructor pair inVector to manage the lifetime of its elements is an example (§3.2.1.2) and all standard-library containers are implemented in similar ways. Importantly, this approach interacts correctly with errorhandling using exceptions. For example, the technique is used for the standard-library lock classes:mutex m; // used to protect access to shared data// ...void f(){unique_lock<mutex> lck {m}; // acquire the mutex m// ...

manipulate shared data ...}A thread will not proceed until lck’s constructor has acquired its mutex, m (§5.3.4). The corresponding destructor releases the resource. So, in this example, unique_lock’s destructor releases themutex when the thread of control leaves f() (through a return, by ‘‘falling off the end of the function,’’ or through an exception throw).This is an application of the ‘‘Resource Acquisition Is Initialization’’ technique (RAII; §3.2.1.2,§13.3).

This technique is fundamental to the idiomatic handling of resources in C++. Containers(such as vector and map), string, and iostream manage their resources (such as file handles and buffers) similarly.5.2.1 unique_ptr and shared_ptrThe examples so far take care of objects defined in a scope, releasing the resources they acquire atthe exit from the scope, but what about objects allocated on the free store? In <memory>, the standard library provides two ‘‘smart pointers’’ to help manage objects on the free store:[1] unique_ptr to represent unique ownership (§34.3.1)[2] shared_ptr to represent shared ownership (§34.3.2)The most basic use of these ‘‘smart pointers’’ is to prevent memory leaks caused by careless programming. For example:void f(int i, int j)// X* vs.

unique_ptr<X>{X∗ p = new X;// allocate a new Xunique_ptr<X> sp {new X};// allocate a new X and give its pointer to unique_ptr// ...Section 5.2.1unique_ptrif (i<99) throw Z{};if (j<77) return;p−>do_something();sp−>do_something();// ...delete p;and shared_ptr113// may throw an exception// may return "early"// may throw an exception// may throw an exception// destroy *p}Here, we ‘‘forgot’’ to delete p if i<99 or if j<77.

On the other hand, unique_ptr ensures that its objectis properly destroyed whichever way we exit f() (by throwing an exception, by executing return, orby ‘‘falling off the end’’). Ironically, we could have solved the problem simply by not using apointer and not using new:void f(int i, int j){X x;// ...}// use a local variableUnfortunately, overuse of new (and of pointers and references) seems to be an increasing problem.However, when you really need the semantics of pointers, unique_ptr is a very lightweightmechanism with no space or time overhead compared to correct use of a built-in pointer. Its furtheruses include passing free-store allocated objects in and out of functions:unique_ptr<X> make_X(int i)// make an X and immediately give it to a unique_ptr{// ... check i, etc.

...return unique_ptr<X>{new X{i}};}A unique_ptr is a handle to an individual object (or an array) in much the same way that a vector isa handle to a sequence of objects. Both control the lifetime of other objects (using RAII) and bothrely on move semantics to make return simple and efficient.The shared_ptr is similar to unique_ptr except that shared_ptrs are copied rather than moved.The shared_ptrs for an object share ownership of an object and that object is destroyed when thelast of its shared_ptrs is destroyed. For example:void f(shared_ptr<fstream>);void g(shared_ptr<fstream>);void user(const string& name, ios_base::openmode mode){shared_ptr<fstream> fp {new fstream(name,mode)};if (!∗fp) throw No_file{}; // make sure the file was properly openedf(fp);g(fp);// ...}114A Tour of C++: Concurrency and UtilitiesChapter 5Now, the file opened by fp’s constructor will be closed by the last function to (explicitly or implicitly) destroy a copy of fp.

Note that f() or g() may spawn a task holding a copy of fp or in someother way store a copy that outlives user(). Thus, shared_ptr provides a form of garbage collectionthat respects the destructor-based resource management of the memory-managed objects. This isneither cost free nor exorbitantly expensive, but does make the lifetime of the shared object hard topredict. Use shared_ptr only if you actually need shared ownership.Given unique_ptr and shared_ptr, we can implement a complete ‘‘no naked new’’ policy(§3.2.1.2) for many programs.

However, these ‘‘smart pointers’’ are still conceptually pointers andtherefore only my second choice for resource management – after containers and other types thatmanage their resources at a higher conceptual level. In particular, shared_ptrs do not in themselvesprovide any rules for which of their owners can read and/or write the shared object. Data races(§41.2.4) and other forms of confusion are not addressed simply by eliminating the resource management issues.Where do we use ‘‘smart pointers’’ (such as unique_ptr) rather than resource handles with operations designed specifically for the resource (such as vector or thread)? Unsurprisingly, the answeris ‘‘when we need pointer semantics.’’• When we share an object, we need pointers (or references) to refer to the shared object, so ashared_ptr becomes the obvious choice (unless there is an obvious single owner).• When we refer to a polymorphic object, we need a pointer (or a reference) because we don’tknow the exact type of the object referred to or even its size), so a unique_ptr becomes theobvious choice.• A shared polymorphic object typically requires shared_ptrs.We do not need to use a pointer to return a collection of objects from a function; a container that isa resource handle will do that simply and efficiently (§3.3.2).5.3 ConcurrencyConcurrency – the execution of several tasks simultaneously – is widely used to improve throughput (by using several processors for a single computation) or to improve responsiveness (by allowing one part of a program to progress while another is waiting for a response).

All modern programming languages provide support for this. The support provided by the C++ standard library isa portable and type-safe variant of what has been used in C++ for more than 20 years and is almostuniversally supported by modern hardware. The standard-library support is primarily aimed at supporting systems-level concurrency rather than directly providing sophisticated higher-level concurrency models; those can be supplied as libraries built using the standard-library facilities.The standard library directly supports concurrent execution of multiple threads in a singleaddress space. To allow that, C++ provides a suitable memory model (§41.2) and a set of atomicoperations (§41.3). However, most users will see concurrency only in terms of the standard libraryand libraries built on top of that.

This section briefly gives examples of the main standard-libraryconcurrency support facilities: threads, mutexes, lock() operations, packaged_tasks, and futures.These features are built directly upon what operating systems offer and do not incur performancepenalties compared with those.Section 5.3.1Tasks and threads1155.3.1 Tasks and threadsWe call a computation that can potentially be executed concurrently with other computations a task.A thread is the system-level representation of a task in a program. A task to be executed concurrently with other tasks is launched by constructing a std::thread (found in <thread>) with the task asits argument. A task is a function or a function object:void f();// functionstruct F {void operator()();};// function object// F’s call operator (§3.4.3)void user(){thread t1 {f};thread t2 {F()};t1.join();t2.join();// f() executes in separate thread// F()() executes in separate thread// wait for t1// wait for t2}The join()s ensure that we don’t exit user() until the threads have completed.

To ‘‘join’’ means to‘‘wait for the thread to terminate.’’Threads of a program share a single address space. In this, threads differ from processes, whichgenerally do not directly share data. Since threads share an address space, they can communicatethrough shared objects (§5.3.4). Such communication is typically controlled by locks or othermechanisms to prevent data races (uncontrolled concurrent access to a variable).Programming concurrent tasks can be very tricky. Consider possible implementations of thetasks f (a function) and F (a function object):void f() { cout << "Hello "; }struct F {void operator()() { cout << "Parallel World!\n"; }};This is an example of a bad error: Here, f and F() each use the object cout without any form of synchronization.

Характеристики

Тип файла
PDF-файл
Размер
18,76 Mb
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6476
Авторов
на СтудИзбе
304
Средний доход
с одного платного файла
Обучение Подробнее