There are a lot of simple rules for the distribution of high-volume supplements. Application of a simple high-flow add-on Process Priority Control

In more early posts, it was said about the high threading in Windows behind the CreateThread and WinAPI add-on, as well as the threading problems in Linux and other * nix systems behind the add-on pthreads. If you are writing in C ++ 11 or newer versions, then you have access to std :: thread and some of the most common threading primitives that have appeared in the whole mov standard. Dal will be shown, as from them pratsyuvati. On view of WinAPI and pthreads, code, writing on std :: thread, є cross-platform.

Note: Guidance code buv conversions to GCC 7.1 and Clang 4.0 on Arch Linux, GCC 5.4 and Clang 3.8 on Ubuntu 16.04 LTS, GCC 5.4 and Clang 3.8 on FreeBSD 11, as well as Visual Studio Community 2017 on Windows 10. , the meanings of the powers of the project. Install CMake 3.8 in Ubuntu 16.04. While the code is compiled behind the addition of Clang, * nix systems are responsible for installing the libc ++ package. For Arch Linux, the package is available on the AUR. Ubuntu є has a libc ++ - dev package, if you can click, you won't be able to get through this code so easily. Worker of descriptions on StackOverflow. For FreeBSD, the project needs to install the cmake-modules package to compile.

M'uteksi

The simplest butt of the victorian trediv and m'utexiv is pointed at the bottom:

#include
#include
#include
#include

Std :: mutex mtx;
static int counter = 0;


for (;;) (
{
std :: lock_guard< std:: mutex >lock (mtx);

break;
int ctr_val = ++ counter;
std :: cout<< "Thread " << tnum << ": counter = " <<
ctr_val<< std:: endl ;
}

}
}

int main () (
std :: vector< std:: thread >threads;
for (int i = 0; i< 10 ; i++ ) {


}

// can "t use const auto & here since .join () is not marked const

thr.join ();
}

Std :: cout<< "Done!" << std:: endl ;
return 0;
}

I respect the wrapping of std :: mutex in std :: lock_guard as before idiomi RAII. This kind of guarantor will ensure that the mutex will be accepted in case of exit from the scopes in any case, including in case of errors. To store a number of mutexes at once with the meta of the std :: scoped_lock. However, I only showed up at C + + 17, and it might not skip. For early versions of C ++, the std :: lock template is functionally analogous, but for correct locking by RAII, it is written in additional code.

RWLock

It is not easy to find out the situation, you have access to readings, not to write. In general, read-write lock is more effective than vikoristovuvati, but RWLock is the same. RWLock can be flooded with multiple read streams, or less with one stream per write. RWLock is used in C ++ for std :: shared_mutex and std :: shared_timed_mutex classes:

#include
#include
#include
#include

// std :: shared_mutex mtx; // will not work with GCC 5.4
std :: shared_timed_mutex mtx;

static int counter = 0;
static const int MAX_COUNTER_VAL = 100;

void thread_proc (int tnum) (
for (;;) (
{
// see also std :: shared_lock
std :: unique_lock< std:: shared_timed_mutex >lock (mtx);
if (counter == MAX_COUNTER_VAL)
break;
int ctr_val = ++ counter;
std :: cout<< "Thread " << tnum << ": counter = " <<
ctr_val<< std:: endl ;
}
std :: this_thread :: sleep_for (std :: chrono :: milliseconds (10));
}
}

int main () (
std :: vector< std:: thread >threads;
for (int i = 0; i< 10 ; i++ ) {
std :: thread thr (thread_proc, i);
threads.emplace_back (std :: move (thr));
}

for (auto & thr: threads) (
thr.join ();
}

Std :: cout<< "Done!" << std:: endl ;
return 0;
}

For the analogue of std :: lock_guard for RWLock, the class std :: unique_lock and std :: shared_lock are used, it is probably because I want to acquire a lock. The class std :: shared_timed_mutex appeared in C ++ 14 and is very useful on all modern platforms (I will not say for mobile attachments, game consoles, and so far). On the view of std :: shared_mutex, there are methods try_lock_for, try_lock_unti and other methods that can be used to request a mutex for a given hour. I strongly suspect that std :: shared_mutex is cheaper than std :: shared_timed_mutex. However, std :: shared_mutex is deprived of its appearance in C ++ 17, and now, it does not appear. Zokrema, GCC 5.4, which is still widely victorious, I do not know about it.

Thread Local Storage

Inodі buvає it is necessary to set the change, on the whole global, but to back it up only one reason. Іnshі streams can bunch up a change, ale the stench may smelt its local meaning. For many, they could see Thread Local Storage, or TLS (not a lot of special ones with Transport Layer Security!). Aside from that, TLS can be used as a sutta for accelerating the generation of pseudo-numbered numbers. TLS application in C ++:

#include
#include
#include
#include

Std :: mutex io_mtx;
thread_local int counter = 0;
static const int MAX_COUNTER_VAL = 10;

void thread_proc (int tnum) (
for (;;) (
counter ++;
if (counter == MAX_COUNTER_VAL)
break;
{
std :: lock_guard< std:: mutex >lock (io_mtx);
std :: cout<< "Thread " << tnum << ": counter = " <<
counter<< std:: endl ;
}
std :: this_thread :: sleep_for (std :: chrono :: milliseconds (10));
}
}

int main () (
std :: vector< std:: thread >threads;
for (int i = 0; i< 10 ; i++ ) {
std :: thread thr (thread_proc, i);
threads.emplace_back (std :: move (thr));
}

for (auto & thr: threads) (
thr.join ();
}

Std :: cout<< "Done!" << std:: endl ;
return 0;
}

Myutex is here victorious for the synchronization of the video console. Synchronization is not required to access thread_local with a change.

Atomic changes

Atomic changes are often used to perform simple operations without victorious operations. For example, you need to increment the filter from the number of streams. Instead of wrapping int to std :: mutex, std :: atomic_int is more efficient. Also, C ++ will propose std :: atomic_char, std :: atomic_bool and many more. Also, on atomic changes, lock-free algorithms and structures are implemented. Of course, it’s because the smell is even more folding in design and sophisticated, and not on all systems it’s better for analogous algorithms and structures of data from locks.

Butt to code:

#include
#include
#include
#include
#include

static std :: atomic_int atomic_counter (0);
static const int MAX_COUNTER_VAL = 100;

Std :: mutex io_mtx;

void thread_proc (int tnum) (
for (;;) (
{
int ctr_val = ++ atomic_counter;
if (ctr_val> = MAX_COUNTER_VAL)
break;

{
std :: lock_guard< std:: mutex >lock (io_mtx);
std :: cout<< "Thread " << tnum << ": counter = " <<
ctr_val<< std:: endl ;
}
}
std :: this_thread :: sleep_for (std :: chrono :: milliseconds (10));
}
}

int main () (
std :: vector< std:: thread >threads;

int nthreads = std :: thread :: hardware_concurrency ();
if (nthreads == 0) nthreads = 2;

for (int i = 0; i< nthreads; i++ ) {
std :: thread thr (thread_proc, i);
threads.emplace_back (std :: move (thr));
}

for (auto & thr: threads) (
thr.join ();
}

Std :: cout<< "Done!" << std:: endl ;
return 0;
}

Brutal respect for the hardware_concurrency procedure. Wonder how many threads are evaluated, but the flow system can be displayed in parallel. For example, on machines with a chotiraynuclear processor, which will be hyper threading, the procedure is turned to the number 8. The procedure can also be turned to zero, if the evaluation is not made too far, or the procedure is simply not implemented.

You can find the information about the robot atomic changes in the assembly language in the notatts cheat sheet for the basic instructions of the assembly x86 / x64.

Visnovok

Naskіlki I bachu, all the truth is unrepentant. So when you write cross-platform additions in C ++ about WinAPI and pthreads, you can forget it. Pure C can also repair cross-platform threads from C11. The stench is still not accepted by Visual Studio (I changed it), and it is unlikely that if it will be. It is no secret that Microsoft doesn’t bother to develop the C ++ support in its own compiler, which will concentrate on C ++.

Behind the scenes, there are a few primitives: std :: condition_variable (_any), std: :( ​​shared_) future, std :: promise, std :: sync and інші. I recommend cppreference.com for more information. You can also read the book C ++ Concurrency in Action. Aleksandr is guilty of getting ahead, as it’s not new, to take revenge on the bugger, and I’ve re-circulated a dozen articles from cppreference.com every day.

The new version of the latest dzherel to the notation, as expected, is on GitHub. And how about you at once write a lot of add-ons in C ++?

Streams and processes are tied to the understanding of the calculating technology. The offense is the last of the instructions, which are guilty of being shown in the singing order. Instructions in the surrounding flows or processes can be displayed in parallel.

Processes run in the operating system and reflect the fact that you need to start using programs or programs. Potik, on the other hand, is in the middle of the process. That is why streams are called "lagging processes". Leather processes are stored from one or several streams. The knowledge of several processes allows the computer "one hour" to visit the factory. The removal of several streams allows the process of distributing the robot for parallel viewing. On a multiprocessor computer, the process flows can be processed on the most common processors. Tse allows the visonuvati to be really parallel to the robot.

Absolutely parallel processing is not expected. Streams may be synchronized. One stream can get the result of this thread, or one thread can get exclusive access to the resource, which is victorious for the other thread. Problems of synchronization є a wider reason for pardons among the rich-flowing subsidiaries. In some cases, you can end up looking for a resource that will not be available. Tse end with a camp, which is called vzaimoblokuvannya.

Perche, you need to learn the process is stored in one stream... In the OS, the skin process is prompted by an address space and a single flow, which is controlled. In fact, the process starts.

One side the process is possible as a way of combining native resources into one group... The process is addressing space, where the text can be avenged with programs and data, as well as resources. Resources є display files, daughter processes, unbreakable emergency updates, signal probes, regional information and a lot of information. Nabagato simpler keruvati resources, having found a process in the form.

From the side, the process can be viewed as a result of the victorious co-commands, or just because... There is a small team leader, which shows the order of the order. Win a register, those who have a lot of updates. Win a stack, to take revenge on the protocol to the process, de on the skin procedure, to the wiklican, but has not yet turned around, introducing the frame. If so, I am guilty of vikonuvatisya in the middle of the process, in order to develop the concept of the flow and the process. The processes are victorious for the grouping of resources, and the streams are for the objects, which, by the way, are sent to the central processor.

The concept of streams in doda before the model process the possibility of a one-hour visit in one and the same middle process of several programs, enough squares. A flow chart that runs in parallel in one process, analogous to a number of processes that runs in parallel on one computer. In the first view, streams include address space, display files and other resources. Another vipadku processes spіlnuyut physical memory, disks, printers and інshih resources. The streams may be deyakі power processes, that їkh inodі call forgiven processes. Termin high-flow rate also victorious to describe the victorious number of streams in one process.

Be-like try to stock up two components:

ob'єkta kernel through any operating system, flow control. In the same place, statistical information about the flow is collected (additional flows are also set up by the core);
stack to thread, which reveals the parameters of all functions and local changes that the flow needs to display the code.

Pidvodyachi mezhu, zrypimo: head of processes from flows, in the fact that the processes are isolated from one to one, so vikoristovuyu the small address space, and the flows, can vikoristovuvati one and the same space (in the middle of the process) at the same time, vikonuyu not engaging one to one. U tsomu polagaє The performance of the buggy streaming program: having broken the add-on into a few last streams, we can improve the productivity, simplify the interface of the clerk and want to scale (if your add-on can be installed on a sophisticated system that will display the streams on your future robots)

1. Potency (thread) is the origin of the message to the code in the process.

2. The process of nothing is not viconious, it is just to serve as a container of streams.

3. Streams are set up in the context of any process, and all life goes through only in its boundary.

4. Streams can visually describe the same code and manipulate the same data, and spirally describe the objects of the kernel, some tables describe how they go over some threads, and processes.

5. So as the streams turn out to be significantly less resources, lower processes, make sure you see your work for the development of additional flows and uniquely start new processes (just go to the rosum).

Bagato-tasking(eng. multitasking) - the power of the operating system, or the middle of the program, to prevent the possibility of parallel (or pseudo-parallel) processing of several processes. Handling the baggage problem of the operating systems can be deprived of the rozpodilnyh computational systems.

File: Screenshot of Debian (Release 7.1, "Wheezy") running the GNOME desktop environment, Firefox, Tor, and VLC Player.jpg

The working style of the current operating system, which adjusts the activity of several processes.

There are 2 types of bugs:

· The process of bug fixing(Applies to the processes - immediately visit the programs). Here the program is the one that has the most important element of the code, which can be used to guide the operating system. Bigger in the house of great koristuvachiv (a robot in a text editor and listening to music).

· In-line bug fixing(based on streams). The smallest element of the kerovan code is potik (one program can make 2 or more tasks at once).

Bagatopotokovist - a special form of bug-tasking has been made.

1 Power of the bagato-tasking center

2 Problems of realizing a bug-related medium

3 History of buggy tasking operating systems

4 Typical pseudo-parallel bug-tasking

o 4.1 Trouble-shooting

o 4.2 Dedicated and cooperative task-solving

o 4.3 Vitality or priority problem-solving (real-time mode)

5 Problem situations in buggy task systems

o 5.1 starvation

o 5.2 Race condition

7 Notes

Powerfulness of the bagato-tasking middle course [ed. redaguvati entry text]

Approximate large-scale tasks of the middle will become purely “rostered resources”, if a singing memory card is attached to the skin department, and it’s always active in the singing interval of the hour.

Nayrozvinenіshі buzgatozdachnі systems and carry out the growth of resources dynamically, if the start at the memory of the memory has fallen asleep for the priority and clamping down on the strategy of the system. There are also many special features:

Skin care has its own priority, as long as I will take away the processor hour and memory

The system of organizing the Chergi plant so that the efforts of the plant have taken resources away from the priorities and strategies of the system

The system of organizing the processing of pererivan, which can be activated, deactivated and seen

· Writing the end of the pledged quantum to the hour, the core of the hour is to translate the staff from the state to the state of readiness, giving resources to the staff. If the memory of the side of the building is not stable, it can be changed to disk (swap), and then through the singing system an hour, it will be updated in the memory

The system will secure the address space of the unauthorized entry of the employees

The system will secure the addressable space of its kernel as an unauthorized entrant

The system of razpiznaє zboi and hovering okremikh zavdan and pinning їkh

The system of virtual confusion for access to resources and annexes, which does not allow dead-end situations of zahalnye hovering from the clearing of blocked resources

The system guarantees the skin care, which will be active early

The system of processing the real hour

The system will secure communication between processes

Problems of realizing a multitasking environment [ed. redaguvati vikhіdny text]

The main difficulty in the implementation of the problem-solving middle course is the hope, which is swirling around the memory of the memory, the development of ills and the reversal, the failure to hang up and the dead-end situations.

In addition to being hopeful, the task of solving the problem is very effective. Vitrati resources on її pіdtrimku not guilty: start the processes and, trust їхnyu robot, quickly interconnect memory.

Bagatopotuzhnost- the power of the platforms (for example, the operating system, virtual machines, etc.) or the programs, which can be used in the process of generating the operating system, can be streams, scho vikonuyutsya "parallel", tobto without a specified order in the hour. For the vikonannya of the workers of such a project, it was possible to reach the effective vikonannya of the resources of the calculating machine.

Such streams I also call streams of viconannya(In English. thread of execution); Inodi are called "threads" (literal translation of English. thread) chi informally "threads".

The essence of the flowing process is a quasi-imaging process on the basis of one selected process, so that all threads are sent to the address space of the process. Besides, all streams to the process can be processed not only by the external address space, but by the external file descriptors. The process, which can be won, is at least one (head) time.

Bagatoning (like the doctrine of the program) is not a trick, nor is it buggy, nor is it buggy, it doesn’t matter to those operating systems that implement buggy, which, as a rule, realizes

Before the reloading of the flow in the program, you can enter the following:

· Simplified programs from deyakie vipadkah for rakhunok vikoristannya address space.

· Naymenshі for the process of time vitrati on the streamline.

· Adjustment of the productivity of the process for the production of parallel processing of the processor calculation and operation of the introduction-vivedennya.

1 Type of implementation of streams

2 Vzaєmodiya streams

· 3 Criticism of terminology

6 Notes

Types of Streams Realization [ed. redaguvati entry text]

· Potik at the expanse of the koristuvach. The skin process creates a thread table, similar to the kernel process tables.

Perevagi and short-term types of such:

1. The duration of the timer is in the middle of one process

2. When vikorystannі blocking system power for the process, the threads are blocked.

3. Foldability of implementation

· Potik near the core. Handle from the table of processes in the open space of the kernel є table of flows.

· "Fibers" (eng. fibers). Dekilka streams in the mode of koristuvach, scho vikonuyutsya in one stream mode of the kernel. Due to the spaciousness of the kernel, there are plenty of resources, in the first place I will have the physical memory that range of the address to the kernel mode for the stack to the kernel mode. To that bulo zaprovadzhno understand the "fiber" - the lodged stream, viconuvany in the regime of koristuvach. The dermal flow can be a mother of "fibers".

Vzaєmodiya streams [ed. redaguvati entry text]

The rich streams of the middle often have problems that are tied to the vicarious streams in parallel with the currents of quiet tributes and attachments. For the sake of solving other problems, such methods of interconnection of flows, such as interconnection (m'uteksi), semaphores, critical sections and podii

· Vzamoviklyuchennya (mutex, m'uteks) - tse ob'єkt synchronization, which will stand in a special signal camp, if there is no flow. Just one little bit of Volodya's tsim about an hour, whatever the moment, the name of such objects (from the English mut ually ex clusive access - viklyucha access) - one-hour access to the zalny resource vyklyuchatsya. For all the necessary things M'utex will be able to provide access to a special resource for other flows. The object can be recursively buried another time by the flow itself, the stopper does not block, but instead of the bagatoraz sound. This, for example, is the critical section of Win32. Tim doesn’t, є і both implementations, as they don’t accept and produce to the mutual blocking of the flow when trying to recursive flooding. Tse FAST_MUTEX in the Windows kernel.

· Semaphores є available resources, which can be added to the decilcom by streams at the same hour, when the pool of resources is not used. Todi additional streams are to blame, docks need a number of resources will not be available. Semaphores are even more effective, some of the stench allows one-hour access to resources. Semaphore є logically extended m'utex - a semaphore with a loader 1 equivalent to a mutex, a loader can be used for more than 1.

· Podії. Ob'kt, that the information about “signaling chi ni” is taken from one bit of information, which means the operation “signaling”, “throwing off the non-signaling mill” and “ochikuvati”. Ochіkuvannya on the signalized podії є the visibility of the operation with undisputed continuation of the stream. Ochіkuvannya on non-signalized podії to produce up to the signal flow until quiet pіr, leaving the beginning (or another phase of sampling in the core of the OS) does not signal the podіyu. You can ochіkuvannya kіlkoh podіy in modes, be it any or all. You can also start the pod, which will automatically drop into the non-signaling camp for the awakening of the first woman - and the only one - to the stream (such an object is victorious as the basis for the implementation of the object "critical section"). Actively run in MS Windows both in koristuvach mode and in kernel mode. A similar object for the Linux kernel is called kwait_queue.

· Critical sections provide synchronization similar to mutexes for the reason that the objects represent the critical sections available in the boundaries of the same process. Substances, mutexes and semaphores can also be victorious in a one-process add-on, protects the implementation of critical sections in some OS (for example, Windows NT), to prevent a larger and more efficient and efficient mechanism of simultaneous and effective synchronization. for a single stream (in the presence of competition) with the help of uniqueness of any system wikklics, which lead to the kernel of the OS. Something like a m'utex object, which is a critical section, you can just one stream at a given moment in an hour, you can roam them in the corner when you have access to remote resources.

· Wise men (condvars). Similar to podiyami, alto not є objects, but occupy the memory - vikoristovuyutsya only the addresses of the wicked, the understanding "in the place of the wicked" is not aware, as it is clever to change the addresses of the previous object. At the end of the day, the establishment of a clever change in the signaling of the camp is not burdensome for itself the same inheritance at times, as for the given moment there are no streams that check for change. The installation of the pod in a similar vypadnaya, the reason for the memory will become "signaled" in the middle of the pod, when the streams are coming, which are going to be ochikuvati on the pod, to continue the display without a secret. For the re-registration of such an object, the operation "sound mutex and check for a clearer change atomic" is also required. Actively vikoristovyatsya in UNIX-sub-OS. Discussions about the ups and downs and shortcomings of Windows and UNIX.

· IO completion port (IOCP). Implementations in the OS core and available through system wikliks object "Cherga" with operations "take the structure at the tail of the Cherga" and "take the structure from the head of the Cherga" The first reason is not to go to the wiklik "favor". The special feature of IOCP is that the structure in the new one can be not only an explicit system wake-up call in the mode of the keystroke, but implicitly in the middle of the OS kernel, which is the result of the completion of an asynchronous operation entered-to-write on one descriptor file. To achieve such an effect, the system wiklik "call the file descriptor from IOCP" is necessary. In general, there is a structure to replace the code of the pardon of the operation entered-vivedennya, and also, for the success of the operation, the number of actually entered any bytes. The implementation of the completion port also interconnects a number of streams, so that one processor / core is sent to remove the structure from the bank. The object is specific for MS Windows, and allows the processing of input power supplies for the server software protection in architecture, since some streams can be bought less for a number of new clients' resources. ).

· ERESOURCE. M'utex, which will be recursively buried, with the semantics of exclusive burying, will be distributed. Semantics: an object can be either vilny, or a flood of a large number of streams, it can be distributed, or a flood of everything in one stream with an exclusive rank. If you try to be flooded, I will break the rule, until the flood is blocked, the docks will not sound like that, we will be allowed to burst into flooding. The same operation is of the TryToAcquire type - it doesn’t block out, or I’ll start, or (if it’s necessary to block it), turn it FALSE, not at all shy. Vikoristovuyutsya in the Windows kernel, especially in file systems - so, for example, whether someone on an open disk file will see the FCB structure, in which two such objects will be able to synchronize access to the file size. One of them - the paging IO resource - is only available exclusively in the image file, and the guarantor, at the moment of loading the files, there is no active input-output from the cache and from the image in memory.

Rundown protection. Documentation references (links are present in header files, albeit in documentation) are included in the Windows kernel. Dispenser with operations "zbilshiti", "change" and "checkati". Clean up the block, leave the operation change, do not change the cell to zero. In addition, the operation of improvement can be improved, and the manifestation of the active in the Danish moment of cleaning up the hour of the message of all operations of improvement.

The butt of a simple bucket-streaming add-on.

Narodzheniy about the reason for the great amount of food about the reason for the abundant flow of supplements from Delphi.

Meta tsyo butt - demonstrate the yak correctly, buuvati dodatokovy dodatok, for the winners of the trivial robots in the near future. As for such an add-on, the transmission of data from the form (visual components) back and forth between the main stream and the robot is secured.

The butt does not pretend to be rotated, but only demonstrates the simplest ways of interconnecting streams. Allowing koristuvachev "shvidenko zlіpiti" (who knows what I don’t like) is correct practiu bugatopotokovy dodatok.
At the new one, everything is reported (on my dummy) commented, ale, as soon as there will be food, put it on.
Already again, I save: Streams - on the right is not easy... If you do not notice that everything is good, it’s a great thing, but often everything will be normal for you, and some of the program will be carried out more and more wonderfully. Behavior of incorrectly written, rich-flowing programs can still be found among the great number of factors, as it is hard to do it at a time.

Otzhe, butt. For convenience, using the code, and attaching the archives from the code of the module and form

unit ExThreadForm;

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

// Constants are victorious when transferring data from the stream to the form behind
// Sent to the newcomers
const
WM_USER_SendMessageMetod = WM_USER + 10;
WM_USER_PostMessageMetod = WM_USER + 11;

type
// describe the class to the thread, the site is tThread
tMyThread = class (tThread)
private
SyncDataN: Integer;
SyncDataS: String;
procedure SyncMetod1;
protected
procedure Execute; override;
public
Param1: String;
Param2: Integer;
Param3: Boolean;
Stopped: Boolean;
LastRandom: Integer;
IterationNo: Integer;
ResultList: tStringList;

Constructor Create (aParam1: String);
destructor Destroy; override;
end;

// describe to the class vicarist potik form
TForm1 = class (TForm)
Label1: TLabel;
Memo1: TMemo;
btnStart: TButton;
btnStop: TButton;
Edit1: TEdit;
Edit2: TEdit;
CheckBox1: TCheckBox;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
procedure btnStartClick (Sender: TObject);
procedure btnStopClick (Sender: TObject);
private
(Private declarations)
MyThread: tMyThread;
procedure EventMyThreadOnTerminate (Sender: tObject);
procedure EventOnSendMessageMetod (var Msg: TMessage); message WM_USER_SendMessageMetod;
the EventOnPostMessageMetod procedure (var Msg: TMessage); message WM_USER_PostMessageMetod;

Public
(Public declarations)
end;

var
Form1: TForm1;

{
Stopped - demonstrates the transfer of data from the form to the stream.
Dodatkovo synchronization not vimag, oskilki є forgive
one-word type, and it is written only in one stream.
}

procedure TForm1.btnStartClick (Sender: TObject);
begin
Randomize (); // insensitiveness to the last message Random () - until the flow cannot handle

// Setting the instance of the object to the stream, by passing the input parameter to it
{
UVAGA!
Constructor to the flow of writing in such a rank,
we will apologize, we will allow you:
1. Controlling the moment of your launch. Especially in large quantities
Allowing before starting to set up a stream, transfer it to the input
parameters, etc.
2. Because If you can do it, it will be saved in the form, then
for self-destructive flow (div. lower) yake when running the flow
you can become something like this, and you will become unreasonable.
}
MyThread: = tMyThread.Create (Form1.Edit1.Text);

// However, we will make the splinters because of the designs, then for some kind of pardons
// last hour of yogo іnіtsіalіzatsії (before launch), mi mаmo yogo samі znischiti
// Why do you want to try / except block
try

// Assigning a completion thread to a thread that is acceptable
// result in the robotic flow, and "overwrite" the data on the new
MyThread.OnTerminate: = EventMyThreadOnTerminate;

// Oscillations of the results are collected in OnTerminate, tobto. to self-abasement
// the flow is known to itself as a turbo and so on
MyThread.FreeOnTerminate: = True;

// Application of transmission of input parameters through the fields of the object-flow, at points
// Installed instance, if there are no launches.
// Especially I, the will of the robot through the parameters of the revised
// constructor (tMyThread.Create)
MyThread.Param2: = StrToInt (Form1.Edit2.Text);

MyThread.Stopped: = False; // some kind of parameter, but change to
// hour for the robot to flow
except
// oskіlіk so far not neglecting and not being able to self-harm
FreeAndNil (MyThread);
// but let me tell you the vinyatkova situation to be overwhelmed in an extraordinary order
raise;
end;

// Oskіlki ob'єkt the flow was successfully set up and set up, after setting the hour to start yogo
MyThread.Resume;

ShowMessage ("Stream of launches");
end;

procedure TForm1.btnStopClick (Sender: TObject);
begin
// If an instance is flowing, then we ask you to zupinitisya
// And it itself is "asked". "Zmusiti" in principle can be, ale tse bude
// Vinyatkovo emergency option
// Streaming kitchen. Tom does not look here.
if Assigned (MyThread) then
MyThread.Stopped: = True
else
ShowMessage ("There are no launches!");
end;

procedure TForm1.EventOnSendMessageMetod (var Msg: TMessage);
begin
// Method for processing synchronous rendering
// WParam has the address of the tMyThread object, in LParam the current LastRandom value to the thread
with tMyThread (Msg.WParam) do begin
Form1.Label3.Caption: = Format ("% d% d% d",);
end;
end;

procedure TForm1.EventOnPostMessageMetod (var Msg: TMessage);
begin
// Method for handling asynchronous rendering
// in WParam the current value of IterationNo, in LParam the current value of LastRandom to the stream
Form1.Label4.Caption: = Format ("% d% d",);
end;

procedure TForm1.EventMyThreadOnTerminate (Sender: tObject);
begin
// IMPORTANT!
// The OnTerminate pod processing method depends on the context of the main
// The thread is guaranteed to be implemented by tThread. That in the new it is possible
// vikoristovuvati be-like power and methods of be-like objects

// About every kind of vipadok, changing, and a copy of the object
if not Assigned (MyThread) then Exit; // if it’s dumb, then it’s nothing

// Rejecting the results in the robot to the stream of the object instance to the stream
Form1.Memo1.Lines.Add (Format ("Eventually ending with the result% d",));
Form1.Memo1.Lines.AddStrings ((Sender as tMyThread) .ResultList);

// The slaughter of an instance of an object to a stream.
// Oskіlki potik we self-devalue (FreeOnTerminate: = True)
// then when the OnTerminate probe is finished, an instance of the stream will be
// deceit (Free), i try to become unrepentant.
// Do not vipadkovo run on this as well, to numb MyThread
// Once again I will respect it - it is not an insignificant object, but only we will overwhelm it. Ob'єkt
// be yourself!
MyThread: = Nil;
end;

constructor tMyThread.Create (aParam1: String);
begin
// Storyumo instance of PRIZUPINED stream (div. Comment when storing instance)
inherited Create (True);

// Implementation of internal facilities (if necessary)
ResultList: = tStringList.Create;

// Otrimannya vikhidnih tributes.

// Copy the input data passed through the parameter
Param1: = aParam1;

// Application of rejecting input data from VCL-components from object-flow constructor
// It is also permissible to use the constructor's wink
/ / Main thread. Otzhe, here you can zvertatsya to VCL-components.
// Ale, I don’t like that;
// About the shape there. It’s not a zrobish for a demonstration.
Param3: = Form1.CheckBox1.Checked;
end;

destructor tMyThread.Destroy;
begin
// Development of internal facilities
FreeAndNil (ResultList);
// lower the base tThread
inherited;
end;

procedure tMyThread.Execute;
var
t: Cardinal;
s: String;
begin
IterationNo: = 0; // filter of results (number of the cycle)

// I applied to the flow є in a cycle, which ends
// otherwise, at the call "pass" the transmissions through the Stopped parameter will be completed,
// or just running 5 cycles
// I will also take a note through the "vichny" cycle.

While True do begin

Inc (IterationNo); // cycle number

LastRandom: = Random (1000); // an alternate number - for demonstration of transferring parameters to the stream before forming

T: = Random (5) +1; // an hour when we are blue, so we don’t end

// Robot is stupid (check the input parameter)
if not Param3 then
Inc (Param2)
else
Dec (Param2);

// Formulate an intermediate result
s: = Format ("% s% 5d% s% d% d",
);

// Dodamo advance result to list of results
ResultList.Add (s);

//// Attach the transfer of the intermediate result to the form

//// Passing through a method that synchronizes is a classic way
//// Incomplete:
//// - method that synchronizes, - call the method to the class on the thread (for access
//// to the fields of the object-flow), ale, for access to the fields of the form, guilty
//// "nobility" about her and the field (ob'єkti)
//// Positions of organizing programs.
//// - the stream will be held until the end of the vikonannya
//// sync method.

//// Perevagi:
//// - standard and versatility
//// - the synchronized method can be used
//// use the fields of the object-stream.
// a copy that is necessary, you need to save the data in
// Special fields of the object object.
SyncDataN: = IterationNo;
SyncDataS: = "Sync" + s;
// in the meantime, to prevent synchronization of the wiklik method
Synchronize (SyncMetod1);

//// Transfer via synchronous message overload (SendMessage)
//// at once, the data can be passed through the parameters of the new (LastRandom),
//// i through the fields of the object, passing the parameter to the address of the instance
//// about the stream - Integer (Self).
//// Incomplete:
//// - the cause is guilty of the nobility handle vіkna formi
//// - when Synchronize, the flow rate will be set to
//// completion of processing by the main thread
//// - vimagaє suttєvih vitrat of the processor hour for a skin wiklik
//// (on the mixing of streams) that is not necessary for even part of the wiklik
//// Perevagi:
//// - like when Synchronize, when processing, you can speed up
//// use the fields of the object-stream


//// Start the thread.
SendMessage (Form1.Handle, WM_USER_SendMessageMetod, Integer (Self), LastRandom);

//// Sending via asynchronous overloading (PostMessage)
//// Oskіlki in tsyom vypadku at the time of rejection of the main stream,
//// If you can, you can end, transferring the address of the instance
//// an object-stream is not allowed!
//// Incomplete:
//// - the reason is guilty of the nobility handle vіkna forma;
//// - through asynchrony, transfer of data can only be done through parameters
//// Nowadays, the sutta will speed up the transfer of the tributes, which may be
//// More than two machine words. Manually pick up Integer transfers, etc.
//// Perevagi:
//// - on the view of the previous methods, there will be no flow
//// signed up, and immediately continue your vikonannya
//// - on the view from the synchronized wiklik, a sample of the view
//// є form method, which is guilty of mother knowledge about the object-flow,
//// for the call of no nobility about the potik, if the data is transferred only
//// Through the parameters of the view. Tobto because there is nothing to know about the form
//// vzagal - only її Handle, which can be passed yak parameter to
//// Start the thread.
PostMessage (Form1.Handle, WM_USER_PostMessageMetod, IterationNo, LastRandom);

//// Reversal of the Mossy Completion

// Reverse completion by parameter
if Stopped then Break;

// Reversal of completion from just one
if IterationNo> = 10 then Break;

Sleep (t * 1000); // Blindmo for t seconds
end;
end;

procedure tMyThread.SyncMetod1;
begin
// Choose a method to wick the Synchronize method.
// So, do not care about those who are in the є method to the thread tMyThread,
// check the context of the main program thread.
// Otzhe, youmu everything is possible, youmu can do everything :)
// Ale pam'yataєmo, it’s not like “messing around”

// Transferred parameters, we can use it from special fields, kudi mi їkh
// Protected before the wiklik.
Form1.Label1.Caption: = SyncDataS;

// For example, from the other fields of the object to the flow, for example, add the tech.
Form1.Label2.Caption: = Format ("% d% d",);
end;

And vzagal, the butt was overwhelmed by such my world on the topic.

Perche:
Here's the rule for bugger-threading programs in Delphi:
In context, it is not possible for the main stream, it’s not possible to turn to the power of the methods of forms, that throng of all the components, which “grow” from tWinControl.

Tse means (forgiven forgiveness) that it is not in the Execute method of the TThread, nor in the other methods / procedures / functions, which are called Execute, not possible Bezposeredno zvertatisya to the zhodnyh authorities and methods of visual components.

Yak robiti is correct.
There are no single recipes. More precisely, the options are so abundant, as well, depending on a specific type, you need to choose it. That until the statti th overpower. Having read that sound, the programmer can be more intelligent and more beautiful than the other’s mind.

Yaksho short on the fingers:

Most of the time, a lot of streaming add-ons become, because if you need to work, I try to trivialize the robot, or if you can immediately start working on the right, do not force the processor too much.

For the first time, the implementation of the robot in the middle of the main stream is to "galvanize" the interface of the koristuvach - the robot doesn’t need to see the cleaning cycle. Yak nasledok - the program does not react to the actions of the koristuvach, and the form is not overlooked, for example, if it is written by the koristuvach.

For another, if the robot has an active exchange of light, then the hour of “idle time” will come. In the ochіkuvannі otrimannya / overpowering danikh, it is possible to work in parallel, for example, once again, it is also possible to enforce / accept danіh.

Іnshі vipadki, ale rіdsche. However, it doesn’t matter. Nini is not about tse.

Now, yak, everything is written. It is natural to look at what is the most frequent vipadok, often used to get used to it. Otzhe.

Robot, winking in an environmentally friendly manner, at the gallant vipad of machotiri days (I don’t know how to name it more precisely):
1. Vychіdni danі
2. Vlasne the robot itself (you can find out from the wiki tributes)
3. Industrial data (for example, information about the rolling mill)
4. Vyhіdni danі (result)

Most often for reading and vivedennya of a large part of the donations for vikoristovuyut of visual components. Ale, as it is said vishche, it is not possible for the stream to turn to the visual components without the middle. Yak bootie?
The Delphi developers will pass the Synchronize method to the TThread class. Here I will not describe those yak yogo zastosovuvati - for a whole є vishchezgadan statty. I’ll tell you that it’s right, don’t expect it it’s true. Є two problems:

In the first place, it was the method of the wicked through Synchronize that it was necessary to visitor in the context of the main stream, and that, as soon as it was displayed, again, the cycle of processing the visitor would not be visible. Otzhe, vono maє vikonuvatisya shvidko, inakshe, we otrimaєmo the same problems, shho and with single-threaded implementation. In the ideal, the method that wicks through Synchronize is guilty of victoriousness only for the brutalization of power and methods of visual objects.

In a different way, the viconannya method through Synchronize, it is “expensive” to satisfy, the viclikan doesn’t need two mixing between streams.

Moreover, offending problems of interconnection, and wiping of wipes: from one side, for the first time, you need to "tweak" the method, so wicked through Synchronize, and from the other, more often than not, more resources are added to the process.

To that, as a matter of fact, it’s necessary to go smartly, and for the young people, you can use different ways of communicating with the flow of light:

Pochatkovі danі
Efforts of the data that are transmitted to the robot, and change before the hour of the robot, requiring the transmission before the next launch, tobto. before the hour of the stream flow. For їх registration in tіlі stream, it is necessary to create їх local copy (call the TThread site in the fields).
As long as you can change data for an hour, you need to access such data through synchronized methods (methods are triggered through Synchronize), or through the fields of the object-flow (TThread sites). Remaining demand for singing care.

Promіzhny and vіdіdni danі
Here, I know, well, there are some ways (in order of my perevag):
- The method of asynchronous supervision over the head window.
Victory to become inviting to see the main window by the programs about the process of passing through the process of transferring an insignificant tribute
- The method of synchronous control over the head window.
Vikoristovutsya beckon for the same purpose as and asynchronously displayed, rather than allowing you to transfer a large amount of money, without opening a copy.
- Synchronized methods, if possible, are combined into one method of transferring a large amount of money.
It is possible to vikoristovuvati and reject the danikh from the form.
- Through the fields of the ob'єkta-flow, secured through the key access.
Report, you can read the statty.

Ex. Briefly, I didn’t know

Clay Breshears

Entry

Methods of realizing bucket-streaming, which are victorious by Intel's faqs, include chotiri basic steps: analysis, development and implementation, improvement and improvement of productivity. The very same pidhid vikorystovutsya for the stemming of a flood-stream supplement from the last program code. Robot with programmed tasks before the hour of the visit of the first, third and fourth stages of visvitlen to reach widely, so as information and implementation of another croc is clearly lacking.

There have been a number of books assigned to parallel algorithms and parallel calculations. In fact, in the case of cich vidannyah it is important to open up the transmission of new, systems with memory and theoretical parallel models of calculation, an hour unparalleled to real nuclear-powered platforms. As soon as you are ready to seriously engage in high-flow programs, you are humorously aware of the knowledge about the development of algorithms for cich models. It’s obvious that the storage of these models is worthwhile, and the developers of software security can do it, so it’s possible to implement them in practice.

Without too much effort, it is possible to say that the development of rich streams of supplements is in front of the creative work, and also the science of science. Read the statistics and learn about the awkward rules to help you expand the base of practical methods for parallel programming and adjusting the efficiency of realizing streaming calculations in your subsidiaries.

Rule 1. See operations that appear in the program code exactly one of the same

Parallel obrobka zastosovna deprived of prior to the operation of the last code, as vikonuyutsya directly from each other. An unforgiving butt of the fact that, as an independent one from one stage, to produce a real one result, є a living room. Robots with no specialties will take on the lot: testers, electricians, plasterers, plumbing fixtures, pokrivelniki, malaria, mulyari, greenery and greenery. Surely, they can't do their best before they finish their work (for example, the cover-makers do not start to robots, as long as they do not awaken the walls, and the malaria do not fudge the prices, do not work) Ale zhalom can say that the people who are in the business are walking right through each other.

One more butt is visible - a working cycle for a DVD rental shop, until a replacement for singing films is needed. Substitution of razpod_lyayut between the workers of the point, which shukayut tsі files in the warehouse. Naturally, as one of the protagonists in the storehouse of a disk, on which records of the film for the part of Audrey Hepburn, the first rank-and-file does not stick out like a shukak boyovy Chergovy with Arnold Schwarzenegger with the new season to the "Friends" serial. Our applications have a lot of problems, all the problems that have been tied up from the days of films in the warehouses, have appeared before, as replacement was needed to the rental point, and the packaging and updating of any replacement that was not fitted to the casing.

In your robots, singingly, you will stumble upon the numbers, the processing of which can be deprived in singing last, and not in parallel, some of the development of iterations, for the cycle to lie down one form of one and the guilt of the viconuvatyya in strict order. A very live butt from the wild nature. Reveal your own deer. Oskilki vynoshuvannya to the fruit is trivial in the middle of the month, then, do not twist, the deer does not appear through the month, but if all the deer arrive at once. However, all of the reindeer would have miraculously stuck to their staff at once, to harness them at the sleigh of Santa Claus.

Rule 2. Stay parallel to the low level of detail

I have two steps to the parallel subline of the last program code: "bottom-up" and "top-down". At the same time, at the stage of the analysis of the code, the segments of the code (the so-called "hot" points) start, on which the part of the hour is indicated by the program. Parallel podіl tsikh segments in the code (as well as vіn mozhliviy) to ensure the maximum increase in productivity.

At the bottom of the mountain, there is a large-flow processing of hot points to the code. As a parallel sub-line of known points of ill-will, then a stack of wiklick programs, which are available for a parallel sub-segment and a visitor to finish a trivial hour. Let’s admit, look at the program, designed for squeezing graphic images. Stressing can be realized behind the help of a number of independent parallel streams, which can be used to build up around the image segments. However, if you want to see the realizability of the high-flowing "hot" points in your mind, do not be unhappy with the analysis of a stack of victories, as a result of which it is possible to know the accessibility for the parallel sub-segment of the segment, which is located on the higher level of the program code. In this rank, you can improve the steps of detailing the parallel processing.

At the “top-down” approach, the robot is analyzed by the program code, and one can see one segment or the other, which can be performed to complete all the tasks set. Since it is obvious that there are no main segments in the code, analyze these warehouses for a joke of independent numbers. Having analyzed the program code, you can see the value of the module code, which will be displayed for the longest processor hour. The implementation of the streaming processing at the dodatku, designated for video coding, is discernible. Parallel processing can be implemented on the lowest level - for independent images of one frame, or on the other - for groups of frames, which can be processed directly from other groups. As the program starts for one-hour processing of several video files, the parallel submission on such a level can be even simpler, and the details of the lower steps.

Before the step of detailing the parallel calculation, it is reasonable to calculate the calculation, which is necessary for the visitor before the synchronization between the flows. In other words, it’s the lower step of the detailing. The thread counting with a high level of detail can lead to the systemic vitrati, tied to the organization of the streams, to rewrite the whole number of corporeal counts, and to be victorious with the creepy streams. Improving the number of streams with a continuous calculation of the accelerated processing process. Traffic baggage with low details of the impact is less than systemic attention and there is more potential for scale, as it can be used for additional organization of additional flows. For the implementation of parallel processing with low detailing, it is recommended to vikoristovuvati pidhid from top to bottom and organize flows on the highest level of the stack of victories.

Rule 3. Lay your code for the flexibility of scale, so that its productivity grows from the growing number of nuclei.

Not long ago, in addition to dual-core processors, chotiriyadern appeared on the market. In addition, Intel has already bared the processor with 80 cores, a huge number of floating point operations in a second. Oscillations of the number of cores in processors will be an hour away from the power, your software code is guilty of the mother of the available potential for scale. Scale is a parameter that can be used to update the report adequately to respond to such changes as to increase system resources (number of cores, memory, bus frequency, etc.) and increase the number of times. As soon as the number of cores in the processors can grow, turn the code, scale up, the productivity of any increase in the size of the system resources.

Rephrasing one of the laws of Northcote Parkinson (C. Northecote Parkinson), it can be said that "the processing of these loans from all available system resources." This means that with the increase in the number of resources (for example, the number of kernels), all the stench, newer ones, will be victorious for the processing of the data. Turn to the programs for the video clip, the view. When the processor has additional cores, it is unlikely that it will be recognized on the size of the crumbled frames - there is no chance of a number of streams to be changed, and the frame is made to change, before the number of pixels is changed for a while. As a result, through the organization of additional flows, the increase of service tributes is growing, and the steps of detailing the parallelism will decrease. For some other scripts, you can add more video files as needed. At the end of the day, the organization of additional streams, as there will be more (or additional) video files, allow the distribution of the entire process without a priori on that stage, when the additional data is generated. I have my own school, supplements with such possibilities, matima has a high potential for scale.

The development and implementation of parallel processing with the test of decomposition of the given will not allow the scale to be adjusted according to the test of the functional decomposition. The number of independent functions in the program code is most often surrounded by that does not change during the execution of the program. Oscillations of the skin square function are seen in the vicinity of the core (apparently, the processor core), then from the increased number of nuclei flows, so that they can be organically organized beforehand, do not increase productivity. From the same time, the models parallel to the decomposition of the data provide the potential for scaling up the programs to the extent that the number of processor kernels grows older and grows larger.

It is possible to navigate in the program code the stream of processing of independent functions is organized; Turning, for example, with the awakening of the booth, looking out. Svoєrіdna meta budіvnistva - to complete a number of independent buildings. However, if there was a need to make more surfaces, you will want to sing along to find additional working specialties (painters, covers, plumbers, etc.). Also, it is necessary to develop programs, as you can adapt to the decomposition of the data, which will result in the improvement of new options. As soon as your code has implemented a functional decomposition, transferring the organization of additional streams from a larger number of processor cores.

Rule 4. Freeze streaming libraries

If for processing tributes at hot spots, the code can be used as a library, just think about the collection of ready-made functions to replace the vlasny code. In a word, do not get lost on the bike, breaking code segments, functions that are already transferred by optimized procedures to the library warehouse. A lot of libraries, including Intel® Math Kernel Library (Intel® MKL) and Intel® Integrated Performance Primitives (Intel® IPP), also have a lot of streaming functionality, optimized for powerful core processors.

Varto respect that during the victorian procedures, the warehouse of high-flow libraries needs to change, that the visitor of these libraries does not fit into the normal flow of the flow. So, as a result of the treatment of the procedure, there are two different flows, as a result of the skin test, the correct results are turned around. As soon as the procedure goes to the outlying wintry libraries, it is possible to win over the tributes, as it is a great sign of the validity of the results. For correct robots with streams, a library procedure is provided as a new one (not just any local area), or synchronized to get access to remote resources. Visnovok: before Tim, as vikoristovuvati at his own program code, be like a library of a third-party virobnik, get familiar with the documentation, before you can get it, you will be able to turn over to the correct robots with streams.

Rule 5. Victory for the required bug-threading model

Admittedly, there is clearly a lack of functionality for a parallel sub-line of all related segments in the code of functions for the warehouse of high-flow libraries, and you have had a chance to think about organizing flows. Do not keep up with the structure of the streams, as the OpenMP library does it justice to the functionality you need.

The downside of explicitly buggy threading is the unfortunateness of accurate keruvanning by streams.

If you only need a parallel resource cycle, or additional dullness, if you give explicit streams, cost you on a different plane, then in this case, the robot will not be able to take over the robot. The faster the implementation of the flowing rate, the more the more the number of pardons in the code, and the higher the additional value.

The OpenMP library is designed for decomposition of data and is especially good for streaming processing of cycles, so that you can work with more information. Unimportant to those who do not have enough decomposition of tribute before they do not have enough decomposition, it is necessary to provide and additional information (for example, a robot teacher or a substitute), which should be used as a means of checking OpenMP. In such a way, OpenMP can be used for the forward organization of streams, to assess the potential productivity gain, the scale and intelligence, as it will be required for a subtle subset of the program code by the method of explicitly flowing.

Rule 6. The result of the robotic program code is not to blame for the persistence of parallel streams

For a last-minute program code, it is easy to complete a viraz, as if it were a viraz. In the case of a high-flow code, the order of displaying flows is not of value and is based on orders of the planner of the operating system. It is strictly apparent, practically unwise to transfer the last of the streams, which are launched for any operation, or for some reason, if the planner launches at the next moment. Forecast by the head of the rank vikoristovuyutsya for a decrease in the hour of reception when vikonanny programs, especially when robots on a platform with a processor, the number of nuclei of a certain minority for the number of organized flows. As a result of blocking through those that require access to an area that is not recorded in the cache memory, otherwise, due to the need for a visonati, it will be fed to the input / output operation, the planner will be able to shut it down and start the sequence, which is ready before launch.

The irrelevant result of non-value in the planning of the flow of the situation and of the winnings of “overtaking the tribute”. Allowed for the fact that there is a singing tendency to change the meaning of the zealous winter doth, as it is the only way of great importance, we can be gracious. At a distance, the order of displaying streams for specific platforms will be lost by ourselves during all launches of the add-on. However, the most recent changes in the system's mill (for example, the distribution of tribute on a hard disk, the memory of the memory, or the display of the display from the nominal frequency of the changed stream of the net) has been established to provoke the correct order of the display. In such a rank, for the program code, which is correct correctly deprives of the singing last of the streams, of the problems associated with the situations of the race of the given and mutual blockages.

I will look at the increase in productivity more beautifully not to interconnect the order of the flow. Suvora, the post-presentation of the streams is allowed only if there is an extreme need, as it should be established in advance of the establishment of the criteria. In the event of such circumstances, the flows are launched in the order specified by the transmission mechanisms of synchronization. For example, two friends can be imagined, as they read a newspaper, they are laid out on the table. First, the stench can read from the bright shvidkistyu, in a different way, you can read the detailed statistics. And here it is not respectful, hto read the spread of the newspaper, first of all - if any time you happen to have a chance to see your friend, you must not turn over the page. At the same time, there is no need to put a lot of money for the hour and the order of reading the articles - friends read it from a shred, and the synchronization between them insists without the middle when the side is turned upside down.

Rule 7. Pick up local streams. If necessary, declare a blockade in the vicinity of the region.

Synchronization will inevitably be added to the system, but it will not accelerate the process of rejecting the results of parallel calculations, but will prevent them from being correct. So, synchronization is required, but it is impossible to sinister. For minimization of synchronization, it is possible to locally collect flows in any area of ​​memory (for example, an array of elements, designated by identifiers of specific flows).

The need for a spilny vikorystannya of team-hour winters in the winter streams of vynikє to finish ridko. Such changes are necessary to expose the skin flow locally. The change in the value of some є industrial streams is also due to the fact that they are not local for all of the streams. In order to increase the number of intermediate results in the same social area, memory is required to be synchronized. You can minimize the possibility of installing it on the system, but it also covers the back area of ​​the yakomoga earlier. For methods of explicitly buggy streaming transfer of application software and interface of local flow capture function, so that you will not be able to see the flow of local data from the ear of one stream segment to the code before the onset of the offensive segment process (or one in one in the offensive segment)

Even though it is not a matter of locally capturing streams, access to the sleeping resources is synchronized for other additional facilities, for example, blocking. At the same time, it is important to correctly recognize the blocking of specific blocks of tribute, which is simpler than the number of blocks of money, as well as the number of blocks of money. A single blocking mechanism, which synchronizes access to some areas of memory, will only be stuck, if all areas are permanently located in the same critical distribution of the program code.

Yak zrobiti, if there is a need for synchronization, access to a great tribute, for example, an array, how can I stock up on 10,000 elements? Organizuvati dine blockuvannya for the whole array - means, melodiously, vuzke misce into a supplement. Do you ever have an organizovuvati blocking for a skin element okremo? Todi, if there are 32 or 64 parallel streams, it will be possible to get access to a large area of ​​memory, and the number of such conflicts is 1%. Happily, the middle is free of gold, so called blocking by module. As a result, N blocking is possible in modulus, the skin of them can be synchronized with access to the N-th part of the foreign area of ​​the data. For example, there are two such blockages organized, one of them will have access to the guys in the array, and the other - to the unpaired ones. In such a case, the flows, which are swollen to the necessary element, start their partnership and set up every blocking. The number of blocks by the module is vibrated from the number of streams and the number of one-hour operation of several streams to one and the same area of ​​memory.

It is very important that synchronization of access to one area of ​​memory is not allowed overnight to the victorious mechanism of blocking. Zgadaimo Segal's law: “Lyudina, yaka is one year old, I firmly know, yaka is one year old. Lyudina, yak is a little old, she's not singing for anything. " It is permissible that access to the change control is carried out by two separate blocks. In any case, the first blocking segment may be faster one segment of the code, and the other - the lowest segment. Todi streams, scho vikonuyut ci segments, dwell in the situation of the race for the backward tributes, before which one hour to twist.

Rule 8. Change the software algorithm if it is necessary for the implementation of bug-threading

The criterion for assessing the productivity of additional data, such as the last, and parallel, є hour of visit. The estimation of the algorithm is asymptotic order. For the theoretical indicator, it is practically possible to assess the productivity of the programs. So, for all the іnh іnh іnnyh minds, supplements with a step of growth O (n log n) (shvidke grade) will be pratsyuvati more for supplements with steps of growth O (n2) (vibіrkove grade), I want the same results of robots.

More beautiful is the asymptotic order of the visitor, the greater the visibility of the parallel program. However, the most efficient last-minute algorithm is not likely to be split into parallel streams. As soon as I "hot" the point, the programs are folded into folding, and on the other side of the stack, there is also a lot of possibilities for realizing the high-flow rate, so there is a lot of thinking about the algorithm of the last Crazy, for preparing the software code before streaming the є інші method.

As an illustration of the remaining hardened, multiple two square matrices are visible. Strassen's algorithm has one of the shortest asymptotic orders of the order: O (n2.81), which is more shorthand, the lower the order is O (n3), the algorithm has a very inefficient investment cycle. According to Strassen's algorithm, the skin matrix extends over a number of sub-matrices, for which there are seven recursive victories for multiplying n / 2 × n / 2 sub-matrices. For the parallelization of recursive victories, you can create a new trend, such as the last vison of these independent multipliers of matrices, as long as the stench does not reach the given size. At such a time, a number of streams will be exponentially growing, and the steps of detailing will be counted, which will be seen by the skin news stream, as the size of the matrix changes. An easy-to-understand option is to organize a pool of seven streams, which can run one hour and display one multiplier of matrices. When the robot is finished, the thread pool is viewed recursively to the Strassen method for multiple views (like the last version of the program code). As long as in the system, as a visitor to such a program, if there are more than eight processor cores, some of them will be easy to use.

The algorithm for multiplying matrices on a basis is simpler to give a parallel sublayer for an additional wasteful inserted cycle. At the same time, the decomposition of the data is stagnant, when the matrix is ​​divided into rows, one hundred or fifty, and the skin from the streams of the display is calculated. The implementation of such an algorithm looks for the additional OpenMP pragmas, which are inserted into each loop, or explicitly organizing streams, like displaying matrices. For a whole more simple one-by-one algorithm, it takes less money for the program code, as opposed to the implementation of Strassen's multithreaded algorithm.

Already, now you know the awkward rules of the effective conversion of the last program code to parallel. If you follow these rules, you will quickly dissolve the large flow of solutions, as the mother will increase the hope, the optimal productivity and the lesser number of high-school projects.

Go to the web-site of the main courses from the high-flow program, go to

What is the most difficult food at the cobs? If I energized the task of the Java-programmer Oleksandr Pryakhin, the answer is: "Bagatopotoknist". Dyakumo yomu for an idea and help at the preparation of the statty!

We have a glimpse of the internal light of the lecture about the processes, we are free from what is the essence of bug-threading, if it’s okay and it’s realizable - with the help of Java. As long as I remember OOP, do not worry: the basic principles are the same.

About flows and turns

There is a lot of flow, there is little understanding of the process. The process is a part of the virtual memory and resources, like OS video for displaying programs. As soon as you can see a few copies of the same programs, the skin system can see the process. In modern browsers, a skin tab can be used to display a process.

You melodiously stuck with the "Dispatcher of the plant" of Windows (in Linux, it is "System Monitor"), and you know that when you start the processes to shut down the system, and the "navazhchi" of them often hang around, that is why it is finished.

Ale koristuvachi love the problem-solving: don’t go out with it - let me see a dozen windows and postribate this-syudi. There is a dilemma: it is necessary to ensure that the robot doesn’t need to update the system at once, and it’s not a galmuval. Admittedly, "zalizu" not to know the needs of the masters - it is necessary to check food on the programmed basis.

We hope that at one hour the processor has set up more commands and more tributes. So we need to fit into the skin quantum, which is larger than the viconious code. Identify the unit of the code yak ob'ykta - і є potik.

Before the foldable right, take it easy, as you break it into a few simple ones. So, when the robot is out of memory: the "important" process is distributed to threads, as it takes up fewer resources, and it is faster to convey the code to the calculator (as the div. Lower).

The skin supplement has one process at least, and the skin process has one reason, which is called the head one because of the consumer.

Riznitsya between flows and processes

    The streams are victorious to memory, to see the processes, and the processes to vimage around the place at the memory. To that, the streams start and end more quickly: the system does not need to see a new address space, but because of this.

    Process the treatment of leather with your own tribute - you can get rid of the smell through the mechanism of interprocess interaction. Streams zvertayutsya until given and resources one one without a middle: when changing one - one is available to all at once. Because you can control the “twinned” in the process, just like the process of controlling only your “daughters”. To that, the commutation between streams is shvid, and the communion between them is organized in a simpler way.

Yaky zvidsi visnovok? If you need to make a great tribute obshyg, beat it into pieces, which can be overflowed with streams, and then take the result in one. It’s more beautiful, it’s not fertile, it’s hungry for resource processes.

Why is the program like Firefox so popular? In addition, the tabbed robot is isolated for the browser - it’s really cool. Even with one process, it is not so, it is not necessary to complete the program as a whole - the possibility of saving would like a part of the tribute.

Also, there is a lot of flow

From mi th go to the head. Bagatopotokov_st - the process of storing rozbit on streams, such as parallel - in one hour - chipped by the processor.

Numerously new options are available between two or more cores, so the interface and other components of the programs do not trust the robot one one.

The programs can run bagatopotoks on single-core processors, and even then the streams can be flashed through: the first one has been patched, they have saved the first step - they have given it to another, they have saved it - they have turned to the first or launched the third one, etc.

People are hunted to screech because they have no two hands. Processes and programs can use mothers of hand styles, which are required for the owner of the project.

Wait for the signal: synchronization in high-volume programs

To realize that the flow of streams will immediately change that very area of ​​the money. Whose winks will the result be praised, and whose wines will be sucked? The robot didn’t lead to rogue with its resources, the flows needed to coordinate their work. To that, the stench is to be exchanged with information from additional signals. It’s because of the people who are in the middle of it that they’ll be able to infect them at the same time. So, the data of all streams about the streaming mill of resources are synchronized.

Basic synchronization

Vzaimoviklyuchennya (mutual exclusion, quickly - mutex) - "great priest", scho to go to the stream, as for the given moment he has the right to pratsyuvati iz zalnye resources. Viklyuchaє access of the other streams to the occupied memory of the memory. Myutex at a supplement can be a bottle, and the stench can be dispersed between processes. Є trick: mutex to the core of the operating system, which is expensive.

Semaphore - Allowing to enclose a number of streams, allowing access to the resource at a particular moment. So, let us know about the option for the processor for the hour to see the code, de vuzki mіstsya. The problem is, how optimal is the number of streams to lie down in the car of the koristuvach.

Podiya - If you sign up to my mind, once this control is transferred to the demand flow. Danimi about podії streams to exchange, how to develop that logically prodovzhuvati dії one one. One, having removed the data, changed the correctness, the third - saved to a hard disk. Podії razrіznyayayutsya for a way to skasuvannya signal about them. As soon as it is necessary to tell about the flow of the stream, for the signal to be delivered, I will manually set the function of the stream. As long as there is only one trick, it is possible to set up a series of automatic discounts. You must stop the signal by itself, in order to go to the stream. For the dull flow control, you can shikuvati in the dark.

Critical section - a large folding mechanism, which is one cycle and a semaphore in a single switch. The chiller allows the start of the semaphore for the required hour. An overwhelming difference is that the core will be deprived of the vapadk, if the section is occupied and it is necessary to turn on the semaphore. At the rush hour, I started to go to the koristuvach mode. It is a pity that the section can be victorious instead of all the middle of one process.

How to implement Java bug-threading

For the robot with Java threads, the class Thread. Creating a new request for a username means opening an instance to the Thread class and calling it with the required code. Zrobiti price can be done in two ways:

    approve the Thread pidclas;

    Implement a Runnable interface in my class to pass instances to the class in the Thread constructor.

For now, we will not bother with those deaf situations (deadlock "ів), if the flows block the robot one by one and hang around - it is too much for an offensive statti. And at once we will go to practice.

Java bug-threading application: ping-pong mutexami

You think that it will be scary at once - to see. The robot with synchronization objects can be seen in the game form: two streams will be thrown by the mutex. Along the way, start a real program, and at one moment in an hour you can just one way you can crush the remotely available data.

There is a list of class that can be used to determine the power of the already familiar Thread, and the method of "hitting the ball" (kickBall) is written:

Public class PingPongThread extends Thread (PingPongThread (String name) (this.setName (name); // rewrite the thread) @Override public void run () (Ball ball = Ball.getBall (); while (ball.isInGame ( )) (kickBall (ball);)) private void kickBall (Ball ball) (if (! ball.getSide (). equals (getName ())) (ball.kick (getName ());)))

Now let's talk about m'yachik. We will not be simple, but remembered: we will be able to grow fast, but it will be different from one side and a little bit of development. For many victorious mutex: we select information about the robot skin from streams - not allow the isolated streams to split one by one. On the 15th hit, the ball is gripped, so you don't hurt much.

Public class Ball (private int kicks = 0; private static Ball instance = new Ball (); private String side = ""; private Ball () () static Ball getBall () (return instance;) synchronized void kick (String playername) (kicks ++; side = playername; System.out.println (kicks + "" + side);) String getSide () (return side;) boolean isInGame () (return (kicks< 15); } }

And now there are two gravitational streams entering the stage. Namely їkh, not wisely slyly, Ping і Pong:

Public class PingPongGame (PingPongThread player1 = new PingPongThread ("Ping"); PingPongThread player2 = new PingPongThread ("Pong"); Ball ball; PingPongGame () (ball = Ball.getBall ();) .start (); player2.start ();))

"A stadium to the people - it is an hour to start a match." Ogolosimo about the opening of the organizationally - the head class has a supplement:

Public class PingPong (public static void main (String args) throws InterruptedException (PingPongGame game = new PingPongGame (); game.startGame ();))

Yak bachite, there is nothing furious here. The price is still less introduced into the flow of flow, but you can still see how it works, and you can experiment - intervene the triviality of the gris not by the number of strokes, but by the hour, for example. We'll turn to those buggy threads - the java.util.concurrent package, the Akka library, and the volatile mechanism are visible. And now let's talk about the implementation of bug-threading in Python.