Introduction to C ++ Builder multi-thread programming technology

Source: Internet
Author: User

  Abstract: This article briefly introduces the significance of multi-threaded programming in Windows, focuses on the issue of developing multi-threaded applications in the C ++ Builder environment, and through the implementation of producer-consumer issues, this helps us better understand the concept of synchronization and its implementation methods.

  Keywords: Multithreading; synchronization; producer-consumer; C ++ Builder

  Thread feasibility

In many cases, you may need to create a thread for the program. Here are some possibilities:

(1) If a multi-Document Interface (MDI) program is created, it is very important to allocate a thread to each window. For example, for an MDI communication program that connects to multiple hosts simultaneously through multiple Modem, if each window has its own thread to communicate with one host, the whole process is much simpler.

(2) If you are using a machine with multiple processors and want to make full use of all possible CPU resources, you need to split the application into multiple threads. In Windows2000, CPU is divided into threads. Therefore, if the program only contains one thread, the program can only use one CPU by default. However, if the program is divided into multiple threads, Windows2000 can run various threads on different CPUs.

(3) When running some tasks in the background, the user is required to continue to use the application for work. This can be easily achieved using threads. For example, you can put some lengthy re-calculation, page formatting, file read/write and other activities in a separate thread so that they can run in the background without affecting the user.

  Synchronization

One of the most challenging questions about writing a multi-threaded program is how to make one thread cooperate with another. This raises a very important issue: synchronization. Synchronization means that processes and threads can communicate with each other to avoid damaging their data capabilities. In Windows, the synchronization problem is caused by the CPU time slice allocation method of Win32 system. Although at a certain time point, there is only one thread occupying the CPU (single CPU) time, but I cannot know when and where the thread is interrupted, in this way, it is especially important to ensure that the data between threads does not break each other. The synchronization problem is so important and interesting. As a result, many scholars have been attracted to study it, which has produced a series of typical process synchronization problems, the typical examples are "producer-consumer problems", "Reader-writer problems", and "Dining Philosophers. This article briefly discusses how to use multi-threaded programming technology to implement "producer-consumer" on the C ++ Builder platform, helping us better understand the concept of synchronization and its implementation methods.

  Producer-consumer problems

The producer-consumer issue is a well-known issue of process synchronization. It describes a group of producer processes that produce messages and provide them to the consumer process for consumption. To enable concurrent execution of producer and consumer processes, a buffer pool with N buffers is set between them. The producer process can put the messages it produces into a buffer zone, the consumer process can get a message consumption from a buffer. Although all producer and consumer processes are asynchronous, they must be synchronized, that is, the consumer process is not allowed to retrieve messages from an empty buffer, the producer process is not allowed to deliver messages to a buffer that is full of messages and has not been removed.

  C ++ Builder multi-threaded Application Programming Basics

1. Use the TThread class provided by C ++ Builder

The VCL Class Library provides a TThread class for Thread Programming. The TThread class encapsulates WindowsAPI about thread mechanism in Windows. For most applications, thread objects can be used in applications to represent execution threads. By encapsulating the content required by the thread, the thread object simplifies the compilation of multi-threaded applications. Note that the thread object cannot control the thread stack size or its security attributes. To control this, you must use the Create Thread () or Begin Thread () function of WindowsAPI.
The TThread class has the following attributes and methods:

1) attributes:

· Priority: Priority attribute. You can set the thread priority.

· Return Value: Return Value attribute. When the thread is introduced, a value is returned to other threads.

· Suincluded: suspends the property. You can determine whether a thread is suspended.

· Terminated: End attribute. Used to indicate whether the thread should be terminated.

· ThreadID: Id property. The ID of the thread throughout the system. This attribute is very useful when using Windows API functions.

2) method:

· Do Terminate: generates an On Terminate event, but does not end thread execution.

· Resume: Wake up a thread to continue execution.

· Suspend: suspends a thread and must be used in pairs with the Resume process.

· Synchronize: A synchronization process called by the main VCL thread.

· Terminate: Set the Terminate attribute to True to abort the thread execution.

· Wait For: waits For the thread to stop and returns the Value of the Return Value attribute.

2. Coordinating threads

When writing code run by a thread, you must consider the behavior of other threads that may be executed synchronously. Note: avoid two threads trying to use the same global object or variable at the same time. In addition, the Code in one thread depends on the results of tasks executed by other threads.

1) avoid simultaneous access

To avoid conflicts with other threads when accessing global objects or variables, you may need to pause the execution of other threads until the thread code completes the operation.

(1) Lock the object. Some objects have built-in locking functions to prevent other threads from using the instance of this object. For example, a canvas object (TCanvas and Its Derived classes) has a Lock () function that prevents other threads from accessing the canvas until the Unlock () function is called. Obviously, this method is only valid for partial classification.

(2) Use important segments. If the object does not provide the built-in locking function, you can use the important section. Like a door, an important section only allows one thread to enter each time. To use an important section, you must create a global instance of TCriticalSection. The TCriticalSection has two functions: Acquire () (to prevent other threads from executing the region) and Release () (to cancel blocking of other threads ).

(3) Use a multi-read, exclusive write synchronization. When an important segment is used to protect the global memory, only one thread can use the memory at a time. This protection may exceed the requirements, especially when there is an object or variable that is frequently read but rarely written. Multiple Threads read the same memory at the same time, but there is no thread to write the memory. The TMultiReadExclusiveWriteSynchronizer object can protect global variables that are frequently read but rarely written. This object is the same as the important section, but it allows multiple threads to read at the same time, as long as there is no thread to write. Each thread that needs to Read memory first needs to call the Begin Read () function (to ensure that no other thread is writing memory). After the thread completes the Read operations on the protected memory, it needs to call End Read () function. Any thread needs to Write to protect the memory. The Begin Write () function must be called to ensure that no other threads read or Write to the memory at present. After the Write operations on the protected memory are completed, the End Write () function is called.

(4) use the Synchronize function: Void _ fast call Synchronize (TThreadMethod & Method );

The parameter Method is a process name without parameters. In this process without parameters, there are some code for accessing VCL. We can call the Synchronize process in the Execute Process to avoid concurrent access to VCL. The specific process during the running of the program is actually notified by the Synchronize process, and then the main thread executes the process without parameters in the parameter list of the Synchronize process at the appropriate time. In the case of multiple threads, the main thread puts the notifications sent from the Synchronize process into the message queue, and then responds to these messages one by one. This mechanism Synchronize achieves synchronization between threads.

2) Wait for other threads

If the thread must wait for another thread to complete a task, the thread can be temporarily interrupted for execution. Then, either wait for the completion of the other thread, or wait for the other thread to know that the task has been completed.

(1) wait until the thread execution ends.

Wait until the execution of another thread ends and use its Wait For () function. The Wait For function is returned only when the thread is terminated. The termination method either completes the Execute () function or is caused by an exception.

(2) wait until the task is completed. Sometimes, you only need to wait for the thread to complete some operations, rather than waiting for the thread to finish the execution. To this end, you can use an event object. The event object (TEvent) should have a global scope so that they can be visible to all threads. Call the TEvent: Set Event () function when a thread is dependent on other threads. Set Event sends a signal so that other threads can check and learn that the operation is complete. To turn off the signal, use the Reset Event () function.

For example, when you have to wait for several threads to complete their execution rather than a single thread. Because you do not know which thread is finished, you cannot use the Wait For () function For a thread. In this case, you can call the Set Event to accumulate the Count value at the end of the thread and send a signal at the end of the last thread to indicate that all threads have ended.

  Multi-threaded application programming example

The following is a multi-threaded application instance that implements "producer-consumer issues. In this example, we construct the TProducerThread (producer thread) and TCustomerThread (Consumer thread) subclasses of two tthreads according to the method described above. The commodities produced and consumed are only an integer. In the process of coordinating production and consumption, TCriticalSection and TEvent are applied. The producer notifies the consumer to start consumption through the Begin Consume object of the TEvent class, and the consumer notifies the producer to start production through the Begin Produce object of the TEent class. There are two producers and one consumer in the program. The TCriticalSection class is used to synchronize objects between two producers. Its running interface 1 is shown.


Figure 1 program running effect

The main source code is as follows:

Producer thread:

Void _ fast call TProducerThread: Execute ()
{
// ---- Place thread code here ----
Int I = 0;
Int j;
While (I <100) // each producer thread produces 100 items
{
Sleep (1000); // latency, for clear display of execution results
If (Form1-> buffer_size> 0) // The buffer pool is not empty, notifying consumers of consumption.
{
Form1-> Begin Consumer-> Set Event ();
}
Form1-> Produce Guard-> Acquire ();
I ++;
StrResult = IntToStr (I );
J = Form1-> buffer_size;
Form1-> Pro

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.