Realization Windows 9x asynchronous serial communication based on multi-threaded technology and custom message programming

zhaozj2021-02-16  98

Realization Windows 9x asynchronous serial communication based on multi-threaded technology and custom message programming

Zhang Zhi Ming Li Rong Yan Wang Lei

Abstract Analysis of asynchronous serial communication program development methods based on Windows 95/98 platforms, combined with development practice, use C Builder language to implement asynchronous serial communication based on multi-threaded technology and message response mechanisms, give programming General steps and detailed explanations. Key words serial communication multi-thread message API event

1 Introduction

Serial communication has the advantages of simple connection, flexible and convenient, and reliable data transfer, and has been widely used in industrial monitoring, data acquisition, and real-time control systems. However, since Windows 95/98 takes a shielded policy for the system underlying operation, users do not allow the hardware I / O port to perform direct operation, serial communication can only be done by calling the API function; while Windows 9x is driven by message queue The program, the DOS interrupt service routine is also difficult to implement, and the real-time and reliability will not be guaranteed; this problem can be effectively solved by multi-tasking processing programming based on thread and messages, and can improve data transmission Throughput and reliability of the application. Windows 9x supports thread-based pre-standard multitasking. Process is an execution instance of an application, and thread is the path executed inside the process. There is at least one main thread each process, and several sub-threads can be operated independently. Fundamentally, the thread is a simplest code unit that can be scheduled by the system. Each thread of the same process has its own set of CPU instructions, a set of CPU registers and a stack, allocated by Windows 9x, requiring CPU time slice, need to be careful Handling the synchronization problem of threads. Thread-based multitasking enables two or more portions of the same program to run simultaneously. A multi-threaded application actually implements a multi-task extension within it, imparts the characteristics of parallel to the code, so that some real-time or random operations can be performed, improve the utilization of CPU, speed up communication The information processing speed of the program. When the operating system assigns the CPU time slice to each thread, the operating system is evaluated by its own scheduling mechanism, prioritize the active thread, the priority level, the active thread, the priority level, and the active thread priority level At the same time, the system scheduler assigns a CPU time slice in a rotation mode. In the first multi-task process, as long as the system scheduler determines that a priority-level thread is ready to run, the system immediately hangs the thread of the priority level (even in the run state), and assigns the CPU time. Priority levels of threads. The open general function enhancement interface provided by the Windows 9x system Win32 API (Application Programming Interface) is a complex function, the collection of messages. Windows 9x is integrated with the support of the serial port and other communication devices and the basic input output driver set, the function used by the serial port is the same as the function of the operation file, and the system is called device control. The data structure of the block DCB configures the serial port and serial communication driver.

2 Basic programming of serial communication

The basic flow of serial communication programming is shown in Figure 1, first call the API function createfile () open and initialize the serial port that needs to operate:

Figure 1 Basic flow of serial communication

Handle Createfile (LPCTSTSTR LPFILENAME, / * To open communication serial name * / dword wdesiredAccess, / * Specify the access method of the serial port, generally set to readable write-how * / dWord dwsharemode, / * Specify the sharing mode of the serial port operation, serial port Can't share, so you can only set up to 0 * / lpsecurity_attributes lpsecurityattributes, / * Set the security properties of the serial port, because the Win9x does not support security properties, this item can only be set to null * / dword dwcreationDistribution, / * For communication serial port, create only Can specify the serial port attribute and the flag for open_existing * / dword dwflagsandattributes, / *, set to file_flag_overlapped, specifying the serial port to communicate in asynchronous mode * / handle htemplateFile / * For serial communication must be set to NULL * /); After successfully open the serial port, the function returns the handle of the serial port. The configuration of the serial device attribute is completed by the following API function: setupComm () Sets the size of the input and output buffers of the serial communication port; modify and set the parameters of the serial operating state by the device control block DCB, such as baud rate, data bit, Communication parameters such as parity blocks, setcommState () write contents in the DCB structure to serial port; additional setcommtimeouts () sets the overflow time of the serial port writing operation. When the event drives the I / O device, set the communication event handle with setcommmask (), Waitcommevent () is used to wait for the communication event. After setting the work is completed, the serial communication can be read in the serial port with readFile (), and WriteFile () is written on the serial port. Call the function closeHandle () at the end of the serial communication to close the serial handle returned by the CREATEFILE function. (Note: Refer to the details of the C Builder Online Help Manual.) In the multi-threaded serial port I / O communication programming, the read, write operations will be considered two different tasks in the same process, create a read Threads and write threads complement the read, write operations of the serial port, and the coordination and synchronization of the thread are implemented by event Event and critical area criticalSECTION object; due to the randomness and real-timeness of the asynchronous serial communication event, the communication thread is required to take precedence over the main thread. Handled, so the priority of each thread is as follows: The priority of the read thread> The priority of the write thread> The priority of the main thread. 3 C Builder 3.0 / 4.0 Support for multi-threaded programming

(1) Use the API functions provided directly from Win32 SDK. Such as CreateThread, SetthreadPriority, ResumeThread, Exitthread, etc., programming is more complicated, and the programming workload is large. (2) TTHREAD thread objects provided by C Builder 3.0 / 4.0. Thread Objects TTHREAD classes encapsulate common methods and data of multi-threaded programming, greatly simplifying multithreaded programming work difficulty, programming as long as they are derived from TTHREAD to create a corresponding instance, often used important attributes / methods : FreeOnterminate Properties: Boolean, when set to true, when the thread ends runs automatically release itself, when set to false, it is necessary to explicitly call the destructor class in the program code to release the destructor class. Its itself. The default is set to False. Priority Properties: Setting the priority of the thread, C Builder defines the enumeration type TTHREADPRIRIRIRIRITY (TPHIGHER, TPLOWER, TPNORMAL, TPHIGHER, TPHIGHEST, TPTIMECRITICRITICRCIL) to indicate the priority of the thread, the default is set to TPNORMAL. Terminated properties: Boolean type, thread end flag. When the value is true, the thread ends, the value is flyse, indicating that the thread is running. Need to check it in the Execute function, end the thread for TRUE. _FastCall TTHREAD (Bool CreateSuspended): The constructor of the object class, if the parameter createsuspend is false, the thread is created automatically, start running immediately; if CreateSuspend is True, the thread is started in a suspend state. Virtual Void_fastCall Execute (Void): Member function, create thread execution code section, must overload this method function in the derived class, add your own program code in the function body, implement specific features. Void_fastcall Synchronize: Synchronization method. The suspended thread itself is executed to handle the control to the main thread, and the function or process specified by the main thread is called by the main thread, and then control the right to control the thread that calls the SYNCHRONIZE method. The Synchronize method avoids the conflict between multi-threads to prevent the program "dead lock". Void_fastCall Terminate (Void): Call this member method function to terminate the running of the thread, and the automatic thread end flag Terminated value is TRUE. 4 multi-threaded programming achieve asynchronous serial communication

With Windows 9X multi-thread programming technology, programming Creating auxiliary thread real-time monitoring serial port communication status, and transmits corresponding messages to the main thread based on the serial port communication monitoring thread, by the main thread analysis. The maximum advantage of multi-threaded serial communication method is that the program has autonomic ability to receive data. Once the auxiliary communication monitoring thread query has been sent to the serial port, the secondary thread automatically receives the data, transmitting data to the main thread. Message, the application can process data transferred by the communication serial port according to the message, and the communication monitoring thread does not occupy the CPU time. Practice programming is derived from the thread object TTREAD class (TcommWritThread), and the serial communication operation is used to monitor and manage the input and output of serial port communication. The reading thread reads the data from the communication serial port and transmits to the main thread process; the write thread will write the data from the main thread to the communication serial output; the main thread is completed, the opening, parameter configuration, and the closed work of the serial port communication resource are completed. Also complete the creation of read / write threads, closes, multithreaded coordination, and data intermediate processing and front-end human machine interaction. Figure 2, Figure 3, 4, respectively, a program structure flowchart, serial write thread flowchart, and serial reading thread flowchart. Figure 2 Asynchronous serial communication program flow chart 3 Write thread flow chart

Figure 4 Reading thread flow chart

In view of the characteristics of serial communication, the access to the communication port and storage area data is accessed by the communication port and storage area data using the event (Event) object and the criticalSECTION object, avoiding conflicts and deadlocks that cause multi-threaded rooms. The role of an event object is to tell other threads a particular event. The relevant API function has createEvent () creates an event object. After the call is successful, use set at () and resetEvent () manually reset the event object status, CloseHandle () releases the event object; WaitForsingleObject () and waitformultipleobjects () functions are waiting for one or more The occurrence of a specific event. The role of the critical area is to protect the shared data between the main thread and the read / write thread, only one thread is allowed to access the protected data. InitializecriticalSection () initializes the critical area object, deleteCriticalSECTION () deletes critical area objects and releases its accounts, EntercriticalSection () and LeaveCriticalSECTION () are entry and exit data protection status, respectively. The thread structure combines the meaning of each object meaning as follows: (1) Sending data Complete event: Write thread is established and waited for the event. The event is generated after the data passed from the communication serial port is successfully transmitted from the communication serial port. (2) Read the data completion event: Read the thread to establish and wait for the event. The read thread monitors the communication serial port state, and the data is successfully read from the communication serial port and the data is sent to the main thread. (3) Communication process error event: The reading thread is established and waits for the event. The application utilizes this event to monitor the error event incurred during the communication process. To this purpose, you need to set HFile to set HFILE in the serial port parameter setting, DWEVTMASK = EV_ERR constant. (4) Write thread / reading thread end event: establish and wait for the event to occur in the constructor of the write thread / reading thread, respectively. Call the Terminate () function to terminate the thread during thread execution. (5) The critical area object: The main thread and write thread define and established, which are used to synchronize the serial port shared by the main thread. Write thread Write data to complete events and thread end events; reading threads waiting for reading data to complete events, communication error events, and thread end events. To implement data exchange between the main thread and the read / write thread, the custom message processing is sent to the main thread after the corresponding event occurs. (1) WM_COMM_WRITE: Write thread Send to the main thread after successfully transmitting data. (2) WM_COMM_READ: The read thread is sent to the main thread after receiving the serial port data. After the main thread receives this message, the received data can be subsequently processed. (3) WM_COMM_ERROR: Send by the read / write thread. Where lParam is unused, WPARAM is used for sign messages, the write thread is 0, and the read thread is 1. The read / write thread sends this message to the main thread when an error occurs during communication, and the main thread hangs the corresponding thread until the communication error event is processed. The main thread sends a data memory unit with the write thread sharing serial port when running, and the data shared is protected by the CriticalSECTION critical area object. Write threads apply for ownership of the critical regions before accessing the shared data, and releases the ownership to exit the critical area after the access is completed. The main thread cannot modify the shared data during this period. Share data; Similarly, the main thread modifies the serial port to protect the data. 5 Conclusion

This article has been successfully applied to the practice of electronic cryptographic door lock network monitoring system in intelligent building monitoring system. Practice has proved that multi-threaded programming implements serial communication to achieve good results for close-range RS232 interface communications and long-distance RS485 interface communications.

Zhang Zhiming (School of Electronic Information Engineering, Northwestern University of Technology) Li Rong Yan (Xi'an 710072, China University of Electronic Information Engineering, Northwestern University of Technology)

1. Hao Jie, Cui Xiaodong, Gong Hui and other translations. Borland C Builder Programming Guide. Beijing: Electronic Industry Press, 19982, Borland C Builder 3.0 / 4.0 Online Help

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

New Post(0)