Application of multithreading technology in VC ++ serial communication program

Source: Internet
Author: User

Research on the Application of multithreading technology in VC ++ serial communication program)

Http://hi.baidu.com/sy451/blog/item/121e1095d536c10c7bf4800f.html


1 Overview
In a variety of modern real-time monitoring systems and communication systems, in Windows 9x/NT using VC ++ serial programming RS-232 is a commonly used means. Windows 9x/NT is a preemptive multi-task operating system. The CPU usage time of a program is determined by the system. Multi-task means that the system can run multiple processes at the same time, and each process can run multiple threads at the same time. A process is a running instance of an application and has its own address space. Each process has a main thread and other threads can be created. A thread is the basic entity used by the operating system to allocate CPU time. The CPU time occupied by each thread is allocated by the system, and the system continuously switches between threads. Threads in a process share the virtual address space of the process. They can access the resources of the process and are in parallel execution. This is the basic concept of multithreading.
2 VC ++ support for Multithreading
Development with MFC is a common VC ++ programming method. In VC ++ 6.0, the thread of the MFC application is represented by the cwinthread object. VC ++ classifies threads into two types: User Interface threads and worker threads. The User Interface thread can provide interface and user interaction, which is usually used to process user input and various events and messages. The worker thread is mainly used to process Background tasks of the program.
Generally, a program does not need to directly create a cwinthread object. by calling the afxbeginthread () function, a cwinthread object is automatically created to start a process. Both threads created above use this function.
The termination of a thread depends on one of the following events: the return of the thread function; the exit of the thread by calling exitthread (); the exit of the thread by calling terminatethread () with the thread handle; and the process of the thread is terminated.
3. Application of multithreading in Serial Communication
3.1 requirements for Thread Synchronization for Serial Communication
All threads of the same process share the virtual address space of the process. In Windows 9x/NT, threads are interrupted at the Assembly level. Therefore, multiple threads may simultaneously access the same object. These objects may be global variables, MFC objects, and MFC APIs. The characteristics of serial communication determine that measures must be taken to synchronize thread execution.
In serial communication, each serial object has only one buffer zone, which is used for sending and receiving. A synchronization mechanism must be set up so that only one operation can be performed at a time, otherwise, communication will fail.
Different threads for serial communication processing must be coordinated. If a thread must wait for the end of another thread to run, it should be suspended to reduce the occupation of CPU resources, the signal sent after the completion of another process (Inter-thread Communication).
VC ++ provides synchronization objects to coordinate multi-thread parallel operations. The following are commonly used:
Csemaphore: a traffic signal object that allows a certain number of threads to access a shared resource. It is often used to control the number of threads that access shared resources.
Cmutex: A mutex object that allows at most one thread to access a certain resource at a time point. When the resource is not occupied, the object is in a signal state. This allows mutual access to shared resources.
Cevent: event object, used to notify other threads of an event, so it can also be used to block access to a resource, wait until the thread releases the resource to make it signal. This method is applicable when a thread waits for an event to be executed.
Ccriticalsection: A critical section object that places a piece of code in the critical section. Only one thread can enter and execute this code. A critical section is only valid in the process where it is created.
3.2 wait Function
Win32 API provides a waiting function that can cause the thread to block its own execution. It stops blocking only when the Monitored object generates a certain signal and continues the thread execution. It means to temporarily suspend the thread to reduce the occupation of CPU resources. In some large monitoring systems, serial communication is only part of transaction processing, so the program execution efficiency must be considered. After the serial port Initialization is complete, it will be in the waiting state for communication events, reduce CPU time consumption and improve program running efficiency.
Common wait functions are waitforsingleobject () and waitformultipleobjects (). The former can monitor a single synchronization object, and the latter can monitor multiple synchronization objects at the same time.
3.3 overlapping I/O methods for Serial Communication
For processing the serial port as a file device, use createfile () to open the serial port and obtain a serial port handle. Setcommstate () is enabled for port configuration, including buffer setting, timeout setting, and data format. You can call the readfile () and writefile () functions to read and write data, and use waitcommevent () to monitor communication events. Closehandle () is used to disable the serial port.
When reading and writing the readfile () and writefile () serial ports, you can adopt synchronous execution or overlapping I/O methods. During synchronous execution, the function is returned only after the execution is completed, so other threads for Synchronous execution will be blocked and the efficiency will decrease. In the overlap mode, the read/write function called will return immediately, i/O operations are performed in the background, so that the thread can process other transactions. In this way, threads can perform read/write operations on the same serial port handle to achieve "Overlap ".
When overlapping I/O is used, the thread must create an overlapped structure for read/write functions. The most important member of this structure is the hevent event handle. It is used as the synchronization object of the thread. When the read/write function is complete, hevent is in a signal state, indicating that the read/write operation can be performed. When the read/write function is not complete, hevent is set to no signal.
4. Implementation of key code of the program
The program creates a serial communication class. The core code of key member functions is given below.
Bool initcomm file: // serial port initialization. Only the code for the key steps is provided here, as shown below
{
Handle m_hcomm;
Commtimeouts m_commtimeouts;
M_hcomm = createfile ("COM1", file: // only Serial Port 1 is used here
Generic_read | generic_write, file: // The Open Type is read/write.
0, file: // open the serial port in exclusive mode
Null, file: // do not set security attributes
Open_existing,
File_flag_overlapped, file: // overlapping I/O mode
0 );
If (m_hcomm = invalid_handle_value) file: // opening failed
{Return false ;}
M_commtimeouts.readintervaltimeout = 1000;
File: // set the timeout value. You should set the timeout value based on your actual needs.
M_commtimeouts.readtotaltimeoutmultiplier = 500;
M_commtimeouts.readtotaltimeoutconstant = 5000;
M_commtimeouts.writetotaltimeoutmultiplier = 500;
M_commtimeouts.writetotaltimeoutconstant = 5000;
If (! Setcommtimeouts (m_hcomm, & m_commtimeouts ))
{Closehandle (m_hcomm );
Return false ;}
Purgecomm (m_hcomm, purge_rxclear | purge_txclear | purge_rxabort | purge_txabort); file: // clear Buffer
Return true;
}
The above is dedicated to COM1 initialization. If you want to use the same function to initialize different serial ports, you must first enter the code critical section before initialization, to ensure that only one serial port is initialized at a certain time.
After the serial port Initialization is successful, you can establish a monitoring thread to handle serial communication events. The following is the key code of the thread.
Uint commthread (lpvoid pparam) file: // The worker thread used to monitor the serial port
{
Bool bresult = false;
If (m_hcomm) file: // check whether the port is opened. Here m_hcomm is the same as above. The author simplifies it here.
Purgecomm (m_hcomm, purge_rxclear | purge_txclear | purge_rxabort | purge_txabort );
For (;) file: // as long as the thread runs, it is in an infinite loop of monitoring port Behavior
{
Bresult = waitcommevent (m_hcomm, & event, & m_ov );
File: // m_ov is a member variable of the overlapped type.
If (! Bresult)
{File: // handle errors}
Else
{
Event = waitformultipleobjects (4, m_hevent, false, infinite );
File: // infinite wait for a set event to occur. The array m_hevent defines the receiving, sending, and closing port events and overlapped hevent events as needed.
Switch (Event)
{File: // read/write Event Response Processing Process, omitted here}
}
Return 0;
}
In this way, the main program can use the afxbeginthread () function to generate a commthread serial port monitoring thread. If you want to monitor all ports at the same time, you can create monitoring threads for the ports respectively.

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.