Implementation (reproduced) in C ++ Builer

xiaoxiao2021-03-05  20

The implementation of multiple threads in C Builer Yinyin is still in the DOS era, people are seeking a multitasking implementation. So there is a TSR type background resident program, which is a representative of the excellent TSR program such as Side Kick, vsafe. The appearance and application of such programs have made users use a computer to bring great convenience, such as Side Kick. We are very convenient to edit the source program without editing the program without having to enter the editor. However, the fatal defect of the DOS single task operating system is destined to impossible for a true multitasking program under DOS. Entering the Windows3.1 era, this situation still has no fundamental changes, and only one thing can be done once. For example, database queries unless the application is very good, the entire system will not respond to the user's input throughout the system during the query. Entering the Windows NT and Windows 9x era, the situation has a thorough change, the operating system has achieved multiple tasks from the true sense (strictly said that Win9X is still not possible). An application, you can have many execution threads when needed, each thread is a small executive, the operating system automatically shares the CPU resources to ensure that any thread cannot lock the system. In this way, when programming, the time-tentative task can be moved to the background, and another thread is accepted by another thread in the front desk. For programming tasks that are relatively high in real-time requirements, such as network customer service, serial communication, etc., multi-threading implementation undoubtedly enhances the availability and stability of the program. In Windows NT and Windows 9x, multi-threaded programming implementation requires calling a range of API functions, such as CreateThread, ResumeThread, etc., more troublesome and easy to make mistakes. We use Inprise's new generation RAD development tool C Builder to easily implement multi-threaded programming. With the old RAD tool Visual Basic and Delphi, C Builer is not only very powerful, but its programming language is C , which is a Windows series operating system for the system development language, which has other programming languages ​​unparalleled advantages. With the TTHRead objects provided by C Builder, multi-threaded programming is very easy to use. So how do you implement it? And take me slowly, let you experience the powerful function of multi-thread. 1. Create a multi-thread program: First, let's introduce the specific steps to implement multithreading. In C Builder, although the TTHRead object illustrates the concept of threads, the TTHREAD object itself is incomplete, requiring new subclasses under TTHREAD, and overloading the Execute method to use thread objects. This can be easily achieved under C Builder. In the C Builder IDE environment, select Menu File | New, select Thread Object in the New column, press OK, then pop up the input box, enter the name mythread of the TTHRead object subclass, so C Builder automatically creates a TTHREAD named TMYTHREAD in TMYTHREAD. Subclass.

At the same time, the editor has a unit called Unit2.cpp, which is the original code of the Tmythread subclass of the Tmythread subclass we created, as follows: #include #pragma hdrstop #include "unit2.h" #pragma package (smart_init) // -------------------- // Important: Methods and Properties Of Objects in vcl can only be // buy in a method caled using synchronize, for example: // / / / Synchronize (UpdateCaption); // // where updatecaption could look like: // // void __fastcall mythread :: updatecaption () // {// form1-> CAPTION = "Updated in a thread"; //} // -------------------- __fastcall mythread :: mythread (Bool createSuspend): tthread (createSuspend) {} ​​// ------------ -------- Void __fastcall mythread :: execute () {// ---- Place thread code here ----} // ---------------- ---- The execute () function is the code where we want to implement in the thread. In the original code contains Unit2.cpp, this can be used by the TMYTHREAD object we created. When using, dynamically create a TMYTHREAD object, use the resume () method in the constructor, then add a new one of our own defined thread TMYTHREAD, the specific execution code is the code for the execute () method overloaded. To load more threads, it doesn't matter, just continue to create a number of TMYTHREAD objects.

We initially realize a custom thread in the program and enable the program to implement multithreaded applications. However, the implementation of multi-threaded applications is not a simple job, but also considers a lot of factors that make multiple threads can coexist and mutually affecting each other. For example, the public variables in the program, the distribution of resources, if handled properly, not only the thread will die, but may even cause the system to crash. In general, pay attention to the processing of shared objects and data in multi-threaded programming, cannot be ignored. So, below we want to talk about the common problems in multi-thread: 2. We all know the use of VCL objects in multithreading, C Builder programming is based on the VCL class library. The properties and methods of accessing VCL objects often need to be accessed in the program. Unfortunately, the VCL class library does not guarantee that the properties and methods of the object are thread access secure (thread_safe), accessing the attribute of the VCL object or calling its method, which may access the memory area that is not protected by other threads. error. Therefore, the TTHREAD object provides a synchronize method that avoids conflicts when accessing the VCL object attribute or calling a method in the thread, avoid conflicts with the Synchronize method to avoid conflicts, so that each thread is coordinated without accidents. error. As follows: void __fastcall TMyThread :: PushTheButton (void) {Button1-> Click ();} void __fastcall TMyThread :: Execute () {... Synchronize ((TThreadMethod) PushTheButton); ...} of Button1-> The call to the click () method is implemented by the Synchronize () method, which automatically avoids multithreading conflicts. In C Builder, although some VCL objects are also thread access secure (such as TFont, TPEN, TBRUSH, etc.), you can use the Sychronize () method to access the property method to improve program performance, but for more Determined VCL objects, but also strongly recommend using the Synchronize () method to ensure the reliability of the program. 3. The usage programming of public data in multi-thread is inevitably share data or objects in multiple threads. In order to avoid catastrophic consequences in multithreading due to simultaneous access to public data blocks, we need to protect public data blocks until a thread ends. This can be implemented through the use of critical sections, and fortunately, in C Builder, it provides us with a TCRiticalSECTION object to make a critical area. This object has two methods, acquire () and release (). It sets the critical area to ensure that only one thread is accessible once.

As shown in the following example: Class mythread: public tthread {... private: tcriticalsection plockx; int x; float y; ...}; void __fastcall mythread :: execute () {... Plockx-> acquire (); / / Here plockx is a global criticalsection variable. X ; y = sin (x); plockx-> release (); ...} This way to publicly protected the public variable x, y through the global TCRITICTION object, avoiding more Conflicts accessed at the same time. 4. Multi-threaded Synchronization When multiple threads are running simultaneously in the program, it is inevitable to encounter the same system resource, or a thread is running to rely on another thread completion, etc., which requires synchronization between threads. Since the thread is running simultaneously, it is impossible to determine the run from the program itself, so that the synchronization of the thread seems difficult to implement. Fortunately, the Windows system is a multi-task operating system. The system kernel provides us with four objects of events, Mutex, Signals (Semaphore), and timer to control the synchronization between the thread. In C Builder, we provide us with TEVENT objects for the creation of Event for us to use. When a thread in the program is waiting to wait for a specific operation instead of waiting for a specific thread to complete, we can easily implement this goal with a TEVENT object. First create a global TEVENT object as all threads monitor. When a thread completes a specific operation, call the TEVENT object's setEvent () method, which will set this flag, and other threads can be done by monitoring this flag. Instead, to cancel this flag, you can call the resetEvent () method. Waiting this flag until you use a waitfor () method in the thread that needs to wait for the operation. Note that the parameter of the waitfor () method is the time waiting for the flag setting. Generally, INFINITE indicates the occurrence of an unlimited wait event, and if other threads are incorrect, it is easy to die (waiting for an event that does not happen). In fact, it is also easy to use the Windows API function to easily implement events (Semaphore) control technology. Especially C Builder, there is an unparalleled advantage in calling Windows API. The functions used include: CreateeMaphore (), CreateEvent (), WaitforsingleObject (), ReleaseSemaphore (), setEvent (), etc., here is not described here. This article combines the programming of the powerful RAD tools developed by Inprise (Borland), making a comparison with multi-threaded programming under Windows. In fact, the realization of multi-threads is not mysterious. After reading this article, you can also have your own multi-threaded program, truly experience the power of multitasking operating systems.

转载请注明原文地址:https://www.9cbs.com/read-36773.html

New Post(0)