Avoiding Problem Areas with Multithread Programs

OverviewHow Do ISample

There are several problems you might encounter in creating, linking, or executing a multithread C program. Some of the more common ones are described here. (For a similar discussion from the MFC point of view, see Multithreading: Programming Tips.)

Problem Probable cause
You get a message box showing that your program caused a protection violation. Many Win32 programming errors cause protection violations. A common cause of protection violations is the indirect assignment of data to null pointers. This results in your program trying to access memory that does not “belong” to it, so a protection violation is issued.

An easy way to detect the cause of a protection violation is to compile your program with debugging information, and then run it through the debugger in the Visual C++ environment. When the protection fault occurs, Windows transfers control to the debugger, and the cursor is positioned on the line that caused the problem.

Your program generates numerous compile and link errors. If you attempt to compile and link a multithread program without defining the symbolic constant _MT, many of the definitions required for the multithread library will be missing. If you are using the Visual C++ development environment, make sure that the Project Settings dialog box specifies multithread libraries. From the command line, define _MT to CL with /MT or /D _MT, or use #define _MT in your program.

You can eliminate many potential problems by setting the compiler’s warning level to one of its highest values and heeding the warning messages. By using the level 3 or level 4 warning level options, you can detect unintentional data conversions, missing function prototypes, and use of non-ANSI features.