C ++ builder advanced

Source: Internet
Author: User

 

(5) Use BCB To Write multi-threaded applications

 

With the popularization of Windows systems worldwide, multithreading technology has been increasingly applied to many software designs. The use of multithreading technology can comprehensively improve the efficiency of application execution. In the past, a series of API functions, such as createthread and resumethread, were basically called to implement multi-threaded programming. They are not easy to control and are prone to errors. After using BCB, I found that it was so easy to write multi-threaded programs! BCB provides us with a powerful tthread class, making multithreaded programming very easy to use. Next, let's start our BCB multi-threaded programming journey with me.

1. Create a multi-threaded program:

First, I will introduce the specific steps for compiling multi-threaded programs in BCB.

In the C ++ builder IDE environment, select the menu filenew, select the thread object in the new column, and press OK. The input box is displayed. enter the name of the tthread object subclass newthread, in this way, C ++ Builder automatically creates a tthread subclass named tnewthread for you. Below are some source code of tnewthread:

_ Fastcall newthread: mythread (bool createsu0000ded)

: Tthread (createsuincluded)

{// Constructor, which can be used to initialize some information

}

Void _ fastcall newthread: Execute ()

{

// The core of a multi-threaded program, used to perform related multi-threaded operations

}

The execute () function in BCB is the location of the task code to be implemented in the thread. When multithreading is used, a tnewthread object is dynamically created and the resume () method is used in the constructor. The code to be executed is reloaded using the execute () method. To create more threads, you only need to create the required number of tnewthreads.

Through the above steps, we basically realized how to create a thread in the program and implemented multi-threaded applications in the program. However, the implementation of multi-threaded applications is not a simple task. Many factors need to be considered to enable multiple threads to coexist in the system without affecting each other. For example, access to public variables and resource allocation in a program. If improperly handled, not only will the thread be deadlocked and in disorder, but may even cause a system crash. In general, you should pay attention to the processing of shared objects and data in multi-threaded programming, and it cannot be ignored. Therefore, the following describes the common problems in multithreading:

2. Use of VCL objects in multiple threads

We all know that C ++ Builder programming is based on the VCL class library. In a program, you often need to access the attributes and methods of the VCL object. Unfortunately, the VCL class library does not guarantee that the attributes and methods of the objects are thread-safe ), accessing the attributes of a VCL object or calling its method may cause an error when accessing the memory area protected by other threads. Therefore, the tthread object provides a synchronize method. When you need to access VCL object attributes in the thread or call methods, you can use the synchronize method to access the attributes or call methods to avoid conflicts, coordinate threads without unexpected errors. As follows:

Void _ fastcall tnewthread: pushthebutton (void)

{

Button1-> click ();

}

Void _ fastcall tnewthread: Execute ()

{

...

Synchronize (tthreadmethod) pushthebutton );

...

}

The call to the button1-> click () method is implemented through the synchronize () method, which can automatically avoid multi-thread access conflicts. In C ++ builder, although some VCL objects are also thread-safe (such as tfont, tpen, and tbrush), sychronize () is not required () methods are used to access and call their attribute methods to improve program performance. However, we strongly recommend that you use the synchronize () method to ensure program reliability for more uncertain VCL objects.

C ++ builder advanced (5) Use BCB To Write multi-threaded applications (2) 3. Use of Public Data in multiple threads

In program design, it is inevitable to share data or objects in multiple threads. To avoid disastrous consequences of simultaneously accessing public data blocks in multithreading, we need to protect public data blocks until a thread ends its access. This can be achieved through the use of the critical section. Fortunately, in C ++ builder, a tcriticalsection object is provided for us to define the critical area. This object has two methods: acquire () and release (). It sets the critical region to ensure that only one thread accesses the region at a time. For example:

Class tnewthread: Public tthread

{

...

PRIVATE:

Tcriticalsection plockx;

Int X;

Float y;

...

};

Void _ fastcall tnewthread: Execute ()

{

...

Plockx-> acquire ();

X ++;

Y = sin (X );

Plockx-> release ();

...

}

In this way, access to the public variable X and Y is protected by the global tcriticalsection object, avoiding the conflict of simultaneous access by multiple threads.

4. multi-thread synchronization

When multiple threads in a program run simultaneously, it is inevitable that the same system resource is used, or the running of one thread depends on the completion of another thread. In this case, synchronization between threads is required. Because the threads run at the same time, the program itself cannot determine the speed of running, making thread synchronization difficult to implement. Fortunately, Windows is a multi-task operating system. The system kernel provides four types of objects, event, mutex, semaphore, and timer, to control synchronization between threads. In C ++ builder, The tevent object for event creation is provided for us.

When the running of a thread in the program is waiting for the completion of a specific operation rather than waiting for the completion of a specific thread, we can easily use the tevent object to achieve this goal. First, create a global tevent object as a flag that can be monitored by all threads. When a thread completes a specific operation, it calls the setevent () method of the tevent object to set this flag. Other threads can monitor this flag to learn about the completion of the operation. To cancel this flag, you can call the resetevent () method. When the waitfor () method is used in the thread that needs to wait for the Operation to complete, it will wait until the flag is set. Note that the parameter of the waitfor () method is the time set by the wait sign. Infinite is generally used to indicate the occurrence of an infinite wait event. If other threads run incorrectly, it is easy to make this thread dead (wait for an event that never happens ).

In fact, using Windows API functions can also easily implement event and semaphore control technologies. In particular, C ++ builder has unparalleled advantages in calling Windows APIs in other languages. The functions used mainly include createsemaphore (), createevent (), waitforsingleobject (), releasesemaphore (), and setevent.

<TD>

 

Related Article

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.