{"id":143,"date":"2006-12-01T16:27:14","date_gmt":"2006-12-01T21:27:14","guid":{"rendered":"http:\/\/bitpost.com\/news\/the-n-habits-of-highly-defective-windows-applications\/"},"modified":"2007-03-29T10:24:07","modified_gmt":"2007-03-29T15:24:07","slug":"the-n-habits-of-highly-defective-windows-applications","status":"publish","type":"page","link":"https:\/\/bitpost.com\/news\/the-n-habits-of-highly-defective-windows-applications\/","title":{"rendered":"The n Habits of Highly Defective Windows Applications"},"content":{"rendered":"<p>This is an ugly dump of the html from <a href=\"http:\/\/www.flounder.com\/badprogram.htm\">this nice writeup<\/a>&#8230;  I just didn&#8217;t want to lose it&#8230;<\/p>\n<p>OK, so it&#8217;s a pun on &quot;The 7 Habits of Highly Effective People&quot;. But<br \/>\nthere are a number of programming techniques that I&#8217;ve found virtually instantly<br \/>\nidentify a defective program. In addition, there are a number of techniques that<br \/>\nmark a program as deeply suspect, and likely to break. Finally, there are a<br \/>\nnumber of techniques which represent poor style, some exceptionally poor, which<br \/>\nviolate principles of modularity and which result in programs that are clumsy to<br \/>\nconstruct, difficult to debug, and impossible to maintain.<\/p>\n<p>Many of these are simple well-known programming issues; for example, the use<br \/>\nof constants where a <b>#define<\/b> is more appropriate. For some reason, I find<br \/>\nthat there is a tendency of programmers to assign certain integers, such as control<br \/>\nIDs, to random hard-coded values. This is a serious problem. But there are a number of<br \/>\ntechniques that also indicate serious flaws in a program. I will summarize these<br \/>\nhere, and clicking on one will link to a discussion of it.<\/p>\n<p>Generally, when I get a program from a client who is having problems, I can solve most of the problems by looking for the<br \/>\nitems I describe here. My track record is that I have been shown code on a page, or on a screen, containing one or more of the<br \/>\ntechniques I discuss here, and I point to it and say &#8220;There&#8217;s your problem!&#8221;, usually within the first 30 seconds. It sometimes takes another ten or twenty minutes to explain to the programmer what has gone wrong as a consequence, and demonstrate exactly what can go wrong in the future, but thus far I&#8217;ve never been wrong in my assessment. On one recent consulting trip, I spotted a<br \/>\n<b> Sleep()<\/b> inside a <b>WaitFor&#8230;<\/b>, and said &#8220;there&#8217;s the problem&#8221;, and then explained &#8220;Your program will fail under the following conditions (a), (b), (c) and the behavior it will exhibit on failure will be (d), (e) and (f)&#8221; and they said &#8220;Yes, that&#8217;s exactly where and how it is failing!&#8221;. As it turned out, there was nothing wrong with that part of the program that a complete rewrite wouldn&#8217;t solve. And the implications on<br \/>\nthe rest of the program architecture were significant, so they now have several weeks&#8217; work to fix the problem, but they now understand why it couldn&#8217;t possibly have worked, except by a great miracle.<br \/>\nI&#8217;ll talk more about the failure mode details later.<\/p>\n<p>I have a little awk script I run on <font face=\"Courier New\">*.cpp<\/font>, and it locates these &#8220;hotspots&#8221;. Usually in less than half an hour I can locate more problems than I have been asked to solve just by studying the code near the hotspots. (I consider this a seriously good revenue generator, since instead of the 1-day or 3-day fix expected, I often get a week or more out of it, since the client, like the one described above, says &#8220;Yes, we never did figure out why that was failing&#8230;&#8221; followed by &#8220;go ahead and fix that while you&#8217;re in there&#8221;<\/p>\n<p>I&#8217;ve put some Severity notifications in these descriptions. My rating of<br \/>\nthese is<\/p>\n<ul>\n<li><b><a name=\"Potentially fatal\">Potentially fatal<\/a>:<\/b> The use of this<br \/>\n    technique shouldn&#8217;t work at all. If it appears to, it is an illusion. <\/li>\n<li><b><a name=\"Serious\">Serious<\/a>: <\/b>There is an excellent chance that<br \/>\n    either the program is defective to start with, or an apparently simple<br \/>\n    change elsewhere in the program will create a defective program. In some<br \/>\n    situations, the fact that the program works at all should be considered<br \/>\n    miraculous.<\/li>\n<li><b><a name=\"Potentially Harmful\">Potentially Harmful<\/a>:<\/b> There is an<br \/>\n    excellent chance that minor changes in the program will result in a<br \/>\n    malfunctioning program, or necessitate gratuitous changes that a proper<br \/>\n  program construction would not have required.<\/li>\n<li><b><a name=\"Inefficient\">Inefficient<\/a><\/b>: this covers most polling<br \/>\n    situations. You will be wasting vast amounts of CPU time and accomplishing<br \/>\n    nothing.<\/li>\n<li><b><a name=\"Poor style\">Poor style<\/a>:<\/b> While the code works, it<br \/>\n    represents poor style of programming. It should be cleaned up to something<br \/>\n    that is manageable.<\/li>\n<li><b><a name=\"Deeply suspect\">Deeply suspect<\/a>:<\/b> While the code works,<br \/>\n    there is almost certainly a better way to accomplish the same task which<br \/>\n    would be simpler, faster, cleaner, or some other suitably positive<br \/>\n    adjective. Generally, there are sometimes valid reasons for using the<br \/>\n    technique specified, but they are fairly rare and easily identified. You<br \/>\n    probably don&#8217;t have one of these reasons.<\/li>\n<\/ul>\n<p>Note that I have not had time to complete all the points in this article, but<br \/>\nit has been sitting in my computer for months and I thought it time to finally<br \/>\nget it out, finished or not!<\/p>\n<h3><b>Threading<\/b><\/h3>\n<ul>\n<li><b><a href=\"#AfxExitThread\">AfxExitThread(), _endthread(), _endthreadex(),<br \/>\n    <\/a><\/b><a href=\"#AfxExitThread\">or<b> ExitThread()<\/b><\/a><\/li>\n<li><b><a href=\"#beginthread\">_beginthread()<\/a><\/b><a href=\"#beginthread\">,<b><br \/>\n    _beginthreadex()<\/b>,<b> <\/b>or<b> CreateThread() <\/b>in an MFC application<\/a><\/li>\n<li><b><a href=\"#CreateThread\">CreateThread<\/a><\/b><a href=\"#CreateThread\"> in<br \/>\n    a C program<\/a><\/li>\n<li><b><a href=\"#TerminateThread\">TerminateThread()<\/a><\/b><\/li>\n<li><a href=\"#Polling process\">Polling for thread completion, include <b>GetThreadExitCode<\/b><\/a><\/li>\n<li><a href=\"#Blocking the main GUI thread\">Blocking the main GUI thread while<br \/>\n    a thread or process completes<\/a><\/li>\n<li><a href=\"#Using PeekMessage anywhere\">Using <b>PeekMessage<\/b> anywhere<\/a>\n<p>    (21-Jun-03) <b> &nbsp;<\/b><\/li>\n<li><a href=\"#volatile\">Failure to use <b>volatile<\/b> in a variable that is<br \/>\n    shared between threads<\/a><\/li>\n<li><a href=\"#Synchronization\">Failure to synchronize access to a variable<br \/>\n    shared between threads<\/a><\/li>\n<li><a href=\"#Overriding the Run() method in a CWinThread class\">Overriding<br \/>\n  the <b>Run()<\/b> method in a <b>CWinThread<\/b> class<\/a><\/p>\n<p>    (1-Mar-05) <b> <img loading=\"lazy\" decoding=\"async\" border=\"0\" src=\"new.gif\" width=\"23\" height=\"12\"><br \/>\n    <\/b><\/li>\n<li>\n  <a href=\"#Putting an infinite loop in the InitInstance handler of a UI thread\"><br \/>\n  Putting an infinite loop in the <b>InitInstance<\/b> handler of a UI thread<\/a><br \/>\n  (1-Mar-05) <b> <img loading=\"lazy\" decoding=\"async\" border=\"0\" src=\"new.gif\" width=\"23\" height=\"12\"><\/p>\n<p>    <\/b><\/li>\n<li><b><a href=\"#SendMessage\">SendMessage<\/a><\/b><a href=\"#SendMessage\"><br \/>\n    between threads, including the implicit <b>SendMessage<\/b> of MFC methods<br \/>\n    that manipulate controls<\/a><\/li>\n<li><a href=\"#Believing a thread starts immediately\">Believing a thread starts<br \/>\n  immediately\/Believing a thread does <i>not<\/i> start immediately<\/a><\/p>\n<p>    (26-Feb-05) <b> <img loading=\"lazy\" decoding=\"async\" border=\"0\" src=\"new.gif\" width=\"23\" height=\"12\"><br \/>\n    <\/b><\/li>\n<\/ul>\n<h3><b>Processes<\/b><\/h3>\n<ul>\n<li><b><a href=\"#ExitProcess\">ExitProcess()<\/a><\/b><\/li>\n<li><b><a href=\"#ExitProcess\">exit()<\/a><\/b><\/li>\n<li><b><a href=\"#PostQuitMessage\">PostQuitMessage <\/a><\/b><a href=\"#PostQuitMessage\">and<b>\n<p>    PostMessage(WM_QUIT)<\/b> on the main GUI thread<\/a><\/li>\n<li><b><a href=\"#PostMessage(WM_CLOSE)\">PostMessage(WM_CLOSE)<\/a><\/b><a href=\"#PostMessage(WM_CLOSE)\"><br \/>\n    on the main window in any context not invoked directly by a user action.<\/a><\/li>\n<li><b><a href=\"#Polling process\">GetExitProcessCode()<\/a><\/b><a href=\"#Polling process\"><br \/>\n    to poll for completion of a process<\/a><\/li>\n<li><a href=\"#Block on Process\">Blocking the main GUI thread while a thread or<br \/>\n    process completes<\/a><\/li>\n<li><a href=\"#setjmp C++\">Using <b>setjmp\/longjmp<\/b> in any C++ program<\/a><\/li>\n<li><a href=\"#setjmp C++\">Using <b>setjmp\/longjmp<\/b> in any GUI program<\/a><\/li>\n<li><a href=\"#setjmp\">Using <b>setjmp\/longjmp<\/b> in any program<\/a><\/li>\n<\/ul>\n<h3>Clipboard<\/h3>\n<ul>\n<li><a href=\"#clipboard\">Any operation that modifies the clipboard that is <i>not<\/i><br \/>\n    related to the user doing an explicit <b>Copy<\/b> or <b>Cut<\/b> operation.<\/a><\/li>\n<\/ul>\n<h3>Timing<\/h3>\n<ul>\n<li><b><a href=\"#Sleep\">Sleep(<i>n<\/i>)<\/a><\/b><\/li>\n<li><b><a href=\"#SleepEx\">SleepEx()<\/a><\/b><a href=\"#SleepEx\"> with any time<br \/>\n    value other than 0 unless asynchronous callback I\/O is being used.<\/a><\/li>\n<li>Any polling that uses realtime as a criterion, unless there is an external<br \/>\n    specification based on hard realtime constraints imposed on the external<br \/>\n    device.<\/li>\n<li>Any use of time that presumes hard realtime can be met by NT<\/li>\n<\/ul>\n<h3>Synchronization<\/h3>\n<ul>\n<li><a href=\"#Using Events for Mutual Exclusion\">Use of events to provide mutual exclusion<\/a><\/li>\n<li><a href=\"#Entering a Critical Section before a Lengthy Operation\">Entering a critical section before any operation that can block, such as<br \/>\n    I\/O, network operations, etc.<\/a><\/li>\n<li><a href=\"#Using PeekMessage anywhere\">Using <b>PeekMessage<\/b> anywhere<\/a>\n<p>    (21-Jun-03) <b> &nbsp;<\/b><\/li>\n<li><b><a href=\"#Polling process\">GetExitProcessCode()<\/a><\/b><a href=\"#Polling process\"><br \/>\n    to poll for completion of a process<\/a><\/li>\n<li><b><a href=\"#TryEnterCriticalSection\">TryEnterCriticalSection()<\/a><\/b><\/li>\n<li><b>WaitFor&#8230;()<\/b> with a time of 0 to poll for completion of a task of<br \/>\n    any sort<\/li>\n<\/ul>\n<h3>Memory Allocation<\/h3>\n<ul>\n<li><a href=\"#malloc\">Using <b>malloc<\/b> or <b>free<\/b> in a C++ program<\/a><\/li>\n<li><a href=\"#GlobalAlloc\">Using <b>GlobalAlloc<\/b>\/<b>GlobalLock<\/b> in any<br \/>\n    context in which its use is not mandated by the API specification (e.g., for<br \/>\n    the clipboard)<\/a><\/li>\n<li><a href=\"#LocalAlloc\">Using <b>LocalAlloc<\/b><\/a><\/li>\n<li><a href=\"#LocalAlloc\">Using <b>LocalFree<\/b> in any context other than<br \/>\n    freeing the buffer returned by <b>FormatMessage<\/b> (or possibly other<br \/>\n    really obscure APIs I am not aware of)<\/a><\/li>\n<li><a href=\"#Array delete\">Deletion of an array of objects without using <b>[<br \/>\n    ]<\/b><\/a><\/li>\n<li><a href=\"#non-const\">The use of non-<b>const<\/b> static variables in<br \/>\n    functions<\/a><\/li>\n<li><a href=\"#Using new without any reason to\">Using <b>new<\/b> without any<br \/>\n  reason to<\/a><br \/>\n    (26-Feb-05) <b> <img loading=\"lazy\" decoding=\"async\" border=\"0\" src=\"new.gif\" width=\"23\" height=\"12\"><br \/>\n    <\/b><\/li>\n<\/ul>\n<h3>Dialogs, forms, and controls<\/h3>\n<ul>\n<li><a href=\"#Dynamic Controls\">Creating controls dynamically<\/a><\/li>\n<li><a href=\"#Using hardwired constants for any size or position\">Using<br \/>\n    hardwired constants anywhere for position or size of anything<\/a><\/li>\n<li><a href=\"#Using hardwired constants for control IDs\">Using hardwired constants for dynamically-created control IDs<\/a><\/li>\n<li><a href=\"#Using GetDlgItem\">Using <b>GetDlgItem<\/b><\/a><\/li>\n<li><a href=\"#Using UpdateData\">Using <b>UpdateData<\/b><\/a><\/li>\n<li><a href=\"#Writing an OnCommand handler\">Writing an<b> OnCommand <\/b><br \/>\n  handler<\/a><\/li>\n<li><a href=\"#Writing a PreTranslateMessage handler\">Writing a <b><br \/>\n  PreTranslateMessage<\/b> handler<\/a><\/li>\n<li><a href=\"#Writing an OnCtlColor handler\">Writing an <b>OnCtlColor<\/b><br \/>\n  handler<\/a><\/li>\n<li><a href=\"#Control Management\">Enabling, disabling, showing, or hiding controls within other event<br \/>\n    handlers such as edit change, button clicks, etc.<\/a><\/li>\n<li><a href=\"#Manipulating Global Variables\">Manipulating static or global variables from a modal or modeless dialog<\/a><\/li>\n<li><a href=\"#Manipulating or calling members of another window class from within a window class\">Manipulating the members<br \/>\n    or calling the methods of any window class from another window class<\/a><\/li>\n<li><a href=\"#Manipulating the controls of a dialog\">Manipulating controls or variables of a dialog from outside the dialog<\/a><\/li>\n<li><a href=\"#Drawing on the dialog\">Drawing on the dialog itself<\/a><\/li>\n<li><a href=\"#Using GetDC\">Using <b>GetDC<\/b><\/a> (5-Nov-04) <b><br \/>\n  <img loading=\"lazy\" decoding=\"async\" border=\"0\" src=\"new.gif\" width=\"23\" height=\"12\"><\/b><\/li>\n<li><a href=\"#Thinking you have one monitor\">Thinking you have one monitor<\/a><b> <\/b>(28-Mar-05) <b><br \/>\n  <img loading=\"lazy\" decoding=\"async\" border=\"0\" src=\"new.gif\" width=\"23\" height=\"12\"><\/b><\/li>\n<\/ul>\n<h3>I\/O<\/h3>\n<ul>\n<li>Using synchronous I\/O in the main GUI thread for slow devices (serial<br \/>\n    ports, networks)<\/li>\n<li>Using synchronous sockets<\/li>\n<li><a href=\"#Entering a Critical Section before a Lengthy Operation\">Entering<br \/>\n    a critical sections around an I\/O operations<\/a><\/li>\n<li><a href=\"#Using SetCurrentDirectory\">Using SetCurrentDirectory\/_chdir<\/a><\/li>\n<\/ul>\n<h3>Program Structure<\/h3>\n<ul>\n<li><a href=\"#Drawing on the dialog\">#include of the application header file in every module<\/a><\/li>\n<li><a href=\"#Manipulating the controls of a dialog\">Manipulating controls or<br \/>\n    variables of a dialog from outside the dialog<\/a><\/li>\n<li><a href=\"#Reaching across classes\">Reaching across views, or from<br \/>\n    mainframe to views, or from application to views ,or most cross-class<br \/>\n    accesses<\/a><\/li>\n<li><a href=\"#Overriding CWinThread::Run\">Overriding <b>CWinApp::Run<\/b> or <b><br \/>\n  CWinThread::Run<\/b><\/a><\/li>\n<\/ul>\n<hr>\n<h3><b><a name=\"AfxExitThread\">AfxExitThread(), _endthread(), <\/a>_endthreadex(),<br \/>\n<\/b><a name=\"AfxExitThread\">or<b> ExitThread()<\/b><\/a><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">potentially fatal<\/a><\/p>\n<p>These will result in erroneous programs. The only correct way to exit a<br \/>\nthread is to either exit from the top-level thread function (straight worker<br \/>\nthreads in MFC or pure C), to do a <b>PostQuitMessage<\/b> from within a UI<br \/>\nthread, or do a <b>PostThreadMessage(WM_QUIT,0,0)<\/b> to a UI thread from<br \/>\noutside it.<\/p>\n<p>Why? Because these functions cause the thread to terminate <i>immediately<\/i>.<br \/>\n(Well, from the viewpoint of the thread, &quot;immediately&quot;; the <b>DLL_THREAD_DETACH<\/b><br \/>\ncalls will still be properly made, so it is not as bad as using <b><a href=\"#TerminateThread\">TerminateThread<\/a><\/b>).<br \/>\nAny pending objects on the stack will not have their destructors called.<br \/>\nResources will leak. Worse still, if some of those objects are synchronization<br \/>\nobjects, such as a <b>CSingleLock<\/b> or <b>CMultiLock<\/b> object, the lock will<br \/>\nnever be released, which will eventually result in the program blocking indefinitely.<\/p>\n<p>So, you claim, you don&#8217;t do any of this? Sure. Right. That&#8217;s this week. A<br \/>\nyear from now, when you are working deep in the thread logic, and discover a<br \/>\nfailure to synchronize, and add one of these, you are now dead. You just don&#8217;t<br \/>\nknow it yet.<\/p>\n<p>Then there&#8217;s the issue of expectations. When a top-level thread function<br \/>\nlooks like this<\/p>\n<pre>\/* static *\/ UINT CMyClass::threadfunc(LPVOID p)\r\n   {\r\n    while(<i>somecondition<\/i>)\r\n       { \/* thread loop *\/\r\n        <i>DoSomething();\r\n<\/i>       } \/* thread loop *\/\r\n    return 0;\r\n   } \/\/ CMyClass::threadfunc<\/pre>\n<p>and you decide to add something useful to the completion, such as<\/p>\n<pre>\/* static *\/ UINT CMyClass::threadfunc(LPVOID p)\r\n   {\r\n    while(<i>somecondition<\/i>)\r\n       { \/* thread loop *\/\r\n        <i>DoSomething();\r\n\r\n<\/i>       } \/* thread loop *\/\r\n    <b>wnd-&gt;PostMessage(UWM_THREAD_COMPLETED);\r\n    <i>clean up thread state<\/i><\/b>\r\n    return 0;\r\n   } \/\/ CMyClass::threadfunc<\/pre>\n<p>this is based on the assumption that you will actually exit the thread<br \/>\nthrough the top-level thread function. Any premature exit of the thread handled<br \/>\nat some lower level will bypass this code. So the program will occasionally<br \/>\nmalfunction in bizarre, possibly non-reproducible ways.&nbsp;<\/p>\n<p>Why would you ever want to exit the thread prematurely? Many valid reasons.<br \/>\nThe file that the thread is supposed to open isn&#8217;t accessible. The network<br \/>\nconnection it was managing was disconnected. You had an internal data structure<br \/>\nconsistency error.<\/p>\n<p>So how <i>do<\/i> you exit a thread prematurely? Simple: throw an exception.<br \/>\nFor example, I would write<\/p>\n<pre>\/* static *\/ UINT CMyClass::threadfunc(LPVOID p)\r\n   {\r\n    while(<i>somecondition<\/i>)\r\n       { \/* thread loop *\/\r\n        <b>TRY \r\n          { \/* try *\/<\/b>\r\n           <i>DoSomething();\r\n          <\/i><b>} \/* try *\/\r\n        CATCH(CMyTerminateException, e)\r\n          { \/* catch *\/\r\n           e-&gt;Delete();\r\n           break;\r\n          } \/* catch *\/<\/b><i>\r\n<\/i>       } \/* thread loop *\/\r\n    <b>wnd-&gt;PostMessage(UWM_THREAD_COMPLETED);\r\n    <i>clean up thread state<\/i><\/b>\r\n    return 0;\r\n   } \/\/ CMyClass::threadfunc<\/pre>\n<p>To define your own exception, you can just derive from the general MFC <b>CException<\/b><br \/>\nclass, e.g.,<\/p>\n<pre>class CMyException : public CException {\r\n    public:\r\n        CMyException() { }\r\n        virtual ~CMyException() { }\r\n};<\/pre>\n<p>If you want to pass parameters in the <b>CMyException<\/b>, just add<br \/>\nparameters to the constructor, and appropriate member variables. To throw the<br \/>\nexception, just write<\/p>\n<pre>throw new CMyException;<\/pre>\n<p>In pure C, you should use the <b>__try<\/b>\/<b>__except<\/b> mechanism and you<br \/>\ncan only throw integer exceptions, but the technique is the same.<\/p>\n<p>Note that <b>__try\/__finally<\/b> will guarantee cleanup, but only if the<br \/>\nthread does not terminate; so while the <b>__finally<\/b> clause is<br \/>\n&quot;guaranteed&quot; to execute, this guarantee applies only if control passes<br \/>\nthrough it. An <b>ExitProcess<\/b>  or <b>ExitThread <\/b>(or anything that<br \/>\nconceals them) will bypass this effect.<\/p>\n<p>Note that in MFC, explicitly terminating a thread is <i>always<\/i> a<br \/>\npotentially fatal operation, because the per-thread handle maps are not cleaned<br \/>\nup, including temporary objects. This will leak storage, as well as leaving<br \/>\nvarious kernel objects orphaned.&nbsp;<b>AfxEndThread<\/b> will actually clean up<br \/>\nthe MFC state correctly, but has all the other hazards, so <i>don&#8217;t do it<\/i>.<\/p>\n<p>Note also that the documentation of <b>_beginthread<\/b> is misleading; it<br \/>\nsuggests that calling <b>_endthread<\/b> &quot;helps to ensure proper recovery of<br \/>\nresources allocated for the thread&quot;, suggesting that it makes sense for you<br \/>\nto do this. Yet it <i>also<\/i> states that , &quot;<b>_endthread<\/b> or <b>_endthreadex<\/b><br \/>\nis called automatically when the thread returns from the routine passed as a<br \/>\nparameter&quot;, without explaining how it knows to call which function (it is<br \/>\nactually because <b>_beginthread<\/b> will implicitly call <b>_endthread<\/b> and <b>_beginthreadex<\/b><\/p>\n<p>will actually call <b>_endthreadex<\/b>, which you can easily see by reading the<br \/>\nsource code for the C runtime in<\/p>\n<pre><i>d<\/i>:\\Program Files\\Microsoft Visual Studio\\vc98\\crt\\src\\thread.c<\/pre>\n<p>and<\/p>\n<pre><i>d<\/i>:\\Program Files\\Microsoft Visual Studio\\vc98\\crt\\src\\threadex.c<\/pre>\n<p>(Providing you installed the C runtime source; if you didn&#8217;t, you should<br \/>\nhave. Go install it now)<\/p>\n<p>What they <i>really<\/i> mean is that you should not call <b>ExitThread<\/b>,<br \/>\nwhich would <i>not<\/i> clean up these resources. There is no justification for<br \/>\nexplicitly calling <b>_endthread<\/b> or <b>_endthreadex<\/b> yourself.<\/p>\n<hr>\n<h3><a name=\"beginthread\">_beginthread(), _beginthreadex(), or CreateThread() in<br \/>\nan MFC program<\/a><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">potentially fatal<\/a><\/p>\n<p>MFC requires certain internal state be set up properly for its correct<br \/>\nfunctioning in a multithreaded environment. This includes creating (and upon<br \/>\ncompletion, destroying) the per-thread handle maps. If you use these methods,<br \/>\nyou bypass MFC&#8217;s maintenance of its internal state.<\/p>\n<p>If you call <i>no<\/i> MFC functions from within the thread, and use <i>no<\/i><br \/>\nMFC objects in any form, you <i>might<\/i> get away with using <b>_beginthread<\/b>,<\/p>\n<p><b>_beginthreadex<\/b> or <b>CreateThread<\/b>. But that means that using <i>any<\/i><br \/>\nMFC function inadvertently opens you to potentially fatal problems. Since there<br \/>\nis essentially no reason to use these, you should use <i>only<\/i> <b>AfxBeginThread<\/b>.<\/p>\n<hr>\n<h3><a name=\"CreateThread\">CreateThread in a C program<\/a><\/h3>\n<p>Severity: <a href=\"#Serious\">serious<\/a>, <a href=\"#Potentially fatal\"><\/p>\n<p>potentially fatal<\/a><\/p>\n<p>The C runtime comes in two flavors: the single-threaded libraries (normal,<br \/>\ndebug, and DLL) and the multithreaded libraries (normal, debug, and DLL). It is <i>essential<\/i><br \/>\nthat you use the multithreaded C library (in any of its forms). Unfortunately,<br \/>\nthe default for a C application is to use the single-threaded library. This<br \/>\nlibrary gains some efficiency at the cost of losing all thread safety.&nbsp;<\/p>\n<p>If you call <b>_beginthread<\/b> or <b>_beginthreadex<\/b>, the functions will<br \/>\ngenerate a compiler error if you have not gone into <b>Project | Settings | Code<br \/>\nGeneration<\/b> and selected the multithreaded library. Therefore, you <i>know<\/i><\/p>\n<p>that if you get a compilation error, you have to enable the multithreaded<br \/>\nlibrary. If, however, you use <b>CreateThread<\/b>, this is an API function,<br \/>\nwhich is always defined. Therefore you can create threads which use the<br \/>\nsingle-threaded C library from multiple threads.<\/p>\n<p>This technique is perfectly safe if you never call any C library functions<br \/>\nfrom the thread. However, maintaining this restriction is difficult over the<br \/>\nlifetime of the program. Since <b>_beginthread<\/b> or, if you need all the<br \/>\ncapabilities, <b>_beginthreadex<\/b>, already provide everything you need to do,<br \/>\nthere is little if any reason for using <b>CreateThread<\/b>.<\/p>\n<hr>\n<h3><a name=\"TerminateThread\">TerminateThread<\/a><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">potentially fatal<\/a><\/p>\n<p>This is always a bad idea. Always. It is to my deep embarrassment that in my<br \/>\nearly writings on threading, in <i>Win32 Programming<\/i>, I made the mistake of<br \/>\nusing this. At least I said that I knew it was a Bad Idea, but I was under a<br \/>\nfair amount of pressure to finish the book, and was not as careful as I should<br \/>\nhave been. I have documented the proper ways of terminating a blocked thread in<br \/>\na <a href=\"workerthreads.htm\">companion essay<\/a>.&nbsp;<\/p>\n<p>The problem with calling <b>TerminateThread<\/b> is that it will <i>instantly<\/i><br \/>\nterminate the thread, and will even suppress the <b>DLL_THREAD_DETACH <\/b>calls<br \/>\nthat many DLLs rely on for correct behavior.<\/p>\n<p>Never use this call. If you think you need it, <i>recode your program so you<br \/>\ndon&#8217;t need it<\/i>.<\/p>\n<hr>\n<h3><a name=\"Polling\">Polling for thread completion<\/a><\/h3>\n<p>Severity: <a href=\"#Inefficient\">inefficient<\/a><\/p>\n<p>A common failure mode in multithreaded programming is to have some thread<br \/>\n&quot;wait&quot; for another by asking &quot;are we there yet? are we there<br \/>\nyet?&quot;. All this accomplishes is to waste a significant amount of CPU time,<br \/>\nsince, unless you have a multiprocessor, the thread that is &quot;waiting&quot;<br \/>\nwill consume its entire time slice asking for a condition <i>that cannot<br \/>\npossibly be set to true<\/i> because during the time that thread is running, the<br \/>\nthread that is being waited for <i>is not running<b> <\/b><\/i>and therefore<br \/>\ncannot possibly change the state!<\/p>\n<p>In a multiprocessor, it means the waiting processor simply wastes a<br \/>\nsignificant amount of its time waiting for a thread to finish; that time could<br \/>\nbe better spent doing something productive, such as running one of the other<br \/>\nthreads of your application.<\/p>\n<p>It doesn&#8217;t matter how you poll; some people use a Boolean variable, waiting<br \/>\nfor it to go <b>TRUE<\/b>, and some use <b>GetThreadExitCode<\/b>. Both of these<br \/>\nare equivalent, and wrong.<\/p>\n<p>There are two techniques for dealing with thread completion. The simplest<br \/>\nmethod, which I will explain why has serious defects in a <a href=\"#Blocking the main GUI thread\">different<br \/>\nsection<\/a> of this essay, is to simply do a <b>WaitFor&#8230;<\/b> operation on the<br \/>\nthread handle. The thread handle remains non-signaled as long as the thread is<br \/>\nrunning (or potentially runnable) and becomes signaled when the thread<br \/>\nterminates. Therefore, the thread that is waiting for the completion uses no CPU<br \/>\ntime while it is waiting. However, since this blocks the waiting thread, and<br \/>\nthat can be the main GUI thread, this is not generally recommended in the main<br \/>\nthread.<\/p>\n<p>The second method is to have the thread <b>PostMessage<\/b> a completion<br \/>\nmessage (user-defined) to the GUI thread. This can be handled by either a view<br \/>\nor the main frame. The thread that receives the message then can enable\/disable<br \/>\ncontrols respond to the completion, and so on.<\/p>\n<hr>\n<h3><a name=\"Blocking the main GUI thread\">Blocking the main GUI thread<\/a><\/h3>\n<p>Severity: <a href=\"#Deeply suspect\">deeply suspect<\/a><\/p>\n<p>A problem that comes up fairly often in the newsgroups deals with the fact<br \/>\nthat the &quot;GUI is non-responsive&quot;, usually to something like a<br \/>\n&quot;Cancel&quot; button not being able to cancel a running thread. It is <i>essential<\/i><br \/>\nthat you not block the GUI thread if you expect features like this to work. It<br \/>\nis generally a Very Bad Idea to block the GUI thread.<\/p>\n<p>The usual excuse is &quot;but I don&#8217;t want to have the user start another<br \/>\nthread&quot; or something like that. Fine. This is trivial. Just disable the<br \/>\ncontrols that would initiate a new thread. For example,<\/p>\n<pre>void CMyView::OnStartComputation()\r\n   {\r\n    AfxBeginThread(...);\r\n    threadrunning = TRUE;\r\n   }<\/pre>\n<pre>void CMyView::OnUpdateStartComputation(CCmdUI * pCmdUI)\r\n   {\r\n    pCmdUI-&gt;Enable(!threadrunning);\r\n   }<\/pre>\n<p>I then use a user-defined message which the thread posts back to the main GUI<br \/>\nthread just after the thread loop completes, using<\/p>\n<pre>wnd-&gt;PostMessage(UWM_THREAD_FINISHED);<\/pre>\n<p>In the handler for <b>wnd<\/b>, add<\/p>\n<pre>ON_MESSAGE(UWM_THREAD_FINISHED, OnThreadFinished)<\/pre>\n<p>or<\/p>\n<pre>ON_REGISTERED_MESSAGE(UWM_THREAD_FINISHED, OnThreadFinished)<\/pre>\n<pre>LRESULT CMyView::OnThreadFinished(WPARAM, LPARAM)\r\n   {\r\n     threadrunning = FALSE;\r\n   }<\/pre>\n<p>For a dialog, read my essay on <a href=\"controls.htm\">dialog control<br \/>\nmanagement<\/a>. What I do is<\/p>\n<pre>void CMyDialog::OnStartComputation()\r\n   {\r\n    AfxBeginThread(...);\r\n    threadrunning = TRUE;\r\n    updateControls();\r\n   }<\/pre>\n<pre>void CMyDialog::updateControls()\r\n   {\r\n    ...\r\n    c_StartComputation.EnableWindow(!threadrunning);\r\n   }<\/pre>\n<p>The only difference in the handler for handling the <b>OnThreadFinished<\/b><br \/>\nevent in a dialog is that I call <b>updateControls()<\/b> explicitly.&nbsp;<\/p>\n<p>For more details on handling user-defined messages, see my essay on <a href=\"messages.htm\">message<br \/>\nmanagement<\/a>.<\/p>\n<p>The use of a blocking call on the main GUI thread, or alternatively a long<br \/>\ncomputation, produces unexpected and generally unpleasant effects on the user<br \/>\ninterface. The failure to put up a wait cursor exacerbates this.<\/p>\n<hr>\n<h3><a name=\"Using PeekMessage anywhere\">Using PeekMessage anywhere<\/a><\/h3>\n<p>Severity: <a href=\"#Serious\">serious<\/a>, <a href=\"#Potentially fatal\">potentially<br \/>\nfatal<\/a>, <a href=\"#Inefficient\">inefficient<\/a>, <a href=\"#Poor style\">poor<br \/>\nstyle<\/a>. (It loses in a <i>lot<\/i> of ways!)<\/p>\n<p style=\"margin-bottom: 0\">First rule: <b>PeekMessage<\/b> is obsolete<\/p>\n<p style=\"margin-top: 0\">Second rule: If you think you need <b>PeekMessage<\/b>,<br \/>\nconsult rule 1.<\/p>\n<p>Actually, <b>PeekMessage <\/b>can be useful, if used with <i>extreme<\/i> care.<br \/>\nFor example, the MFC message pump uses it, and that code demands very careful<br \/>\nstudy if you ever think you want to use <b>PeekMessage<\/b>. It is subtle code.<br \/>\nIf you cannot be at least as subtle as this code, don&#8217;t even consider trying to<br \/>\nuse it.<\/p>\n<p>But in most cases, just pretend you never heard of <b>PeekMessage<\/b>. Most<br \/>\npeople who try to use it get it so badly wrong that its very existence has<br \/>\nnegative effect on program quality. You are always safe if you apply the two<br \/>\nrules above. While they are a heuristic for testing the validity of a program,<br \/>\none of my criteria for determining if a program is seriously defective is the<br \/>\nmere presence of this API call. In all cases I have seen this used, it has been<br \/>\nused incorrectly. So as a simple heuristic I can state that nearly everyone gets<br \/>\nit wrong, and therefore, its very presence is a good indicator of a<br \/>\nfundamentally flawed program design.<\/p>\n<p>If you think you have to use it, you are almost certainly better off using<br \/>\nthreads. But I&#8217;ve seen some pretty bad code when threads are used. So if you<br \/>\nthink you need it in a single-threaded program, your structure is probably<br \/>\nwrong, and you should have used multiple threads. And if you think you need it<br \/>\nin a multithreaded application, you&#8217;re almost certainly wrong, since there is<br \/>\nnothing meaningful it can do.<\/p>\n<p>For example, here is an adaptation from a piece of code I found on the MFC<br \/>\nnewsgroup. It is actually a hybrid of several serious errors I&#8217;ve found in<br \/>\nmultithreaded programs. I decided to discuss all of these in one synthesized<br \/>\nexample.<\/p>\n<pre>\/\/ The global variable that controls and reports the thread state\r\nBOOL running = FALSE;\r\nCRITICAL_SECTION lock;\r\n\r\nvoid CMyClass::OnInitThread()\r\n  {\r\n   EnterCriticalSection(&amp;lock);\r\n   running = TRUE;\r\n   LeaveCriticalSection(&amp;lock);\r\n   AfxBeginThread(threadfunc, parms);\r\n   \/\/ Do not block the GUI thread while the worker is running\r\n   while(running)\r\n     {\r\n      MSG msg;\r\n      if(PeekMessage(&amp;msg, 0, 0, NULL, PM_REMOVE))\r\n        { \r\n         TranslateMessage(&amp;msg);\r\n         DispatchMessage(&amp;msg);\r\n        }\r\n     }\r\n\r\n   DoSomething();\r\n  }<\/pre>\n<pre>UINT threadfunc(LPVOID p)\r\n   {\r\n    BOOL isrunning;\r\n    while(TRUE)\r\n      {\r\n       EnterCriticalSection(&amp;lock);\r\n       isrunning = running\r\n       LeaveCriticalSection(&amp;lock);\r\n       if(!isrunning)\r\n          break;\r\n       ...do thread thing here...\r\n       if(thread_has_completed_its_work)\r\n         { \r\n          EnterCriticalSection(&amp;lock);\r\n          running = FALSE;\r\n          LeaveCriticalSection(&amp;lock);\r\n         }\r\n      }\r\n    }<\/pre>\n<p>What&#8217;s Wrong With This Picture?&nbsp;<\/p>\n<p>To be blunt, nearly everything. The <b>AfxBeginThread<\/b> is salvageable, as<br \/>\nis the code represented by the &quot;&#8230;do thread thing here&#8230;&quot;. The test<br \/>\nfor the thread having completed its work. The function call for doing something<br \/>\nwhen the thread has finished. Nothing else is salvageable. This is a horror of<br \/>\nthe first order.<\/p>\n<p>First, there is a global variable in use. There is no need for a global<br \/>\nvariable. There are a lot of ways of dealing with this, but a global variable is<br \/>\nan indication there is something wrong with the structure. See, for example, my<br \/>\nessays on <a href=\"workerthreads.htm\">worker threads<\/a>, and on <a href=\"callbacks.htm\">callbacks<\/a>.<br \/>\nThese show why you would <i>not<\/i> ever need a global variable.<\/p>\n<p>Then there is the global thread function. This is not necessary. This can be<br \/>\na static class member function (again, see my previously-cited essays on worker<br \/>\nthreads and callbacks).<\/p>\n<p>The <b>BOOL<\/b> variable access is carefully synchronized, which is<br \/>\nunnecessary, and it is not declared <b>volatile<\/b>, which <i>is<\/i> necessary.<\/p>\n<p>But the worst horror of all is the <b>PeekMessage<\/b> loop with its<br \/>\naccompanying comment. This is absolutely, positively incorrect program<br \/>\nstructure. The failure in thinking here is that the actions which must follow<br \/>\nthe thread completion must physically follow the thread invocation, in the same<br \/>\nfunction in which the thread invocation appears. This is completely nonsensical.<br \/>\nThe completion actions are syntactically unrelated to the thread initiation.<br \/>\nThey are only required to <i>temporally<\/i> follow the execution of the thread.<\/p>\n<p>The <b>PeekMessage<\/b> loop is absurd here. It means that while the thread is<br \/>\nrunning, half the CPU cycles go to running a thread that is doing absolutely <i>nothing<\/i><br \/>\nbut consuming CPU cycles in a completely pointless and nonproductive fashion!<\/p>\n<p>The correct solution is to get rid of the <b>PeekMessage<\/b> loop entirely.<br \/>\nThere is no justification for its existence.<\/p>\n<p>One of several correct approaches can be characterized by the code below:<\/p>\n<pre>class CMyWndClass : public CSomeWindowBaseClass {\r\n    ... lots of stuff here\r\n    protected:\r\n      volatile BOOL running;\r\n      static UINT threadfunc(LPVOID p);\r\n      void RunThread();\r\n      afx_msg LRESULT OnThreadFinished(WPARAM, LPARAM);\r\n};\r\n\r\nvoid CMyWndClass::OnInitiateThread()\r\n   {\r\n    running = FALSE; \r\n    updateControls(); \/\/ dialogs only\r\n    AfxBeginThread(threadfunc, this);\r\n   } <\/pre>\n<p>That&#8217;s all that is required. Note that there is absolutely nothing else<br \/>\nhappens in this function! That&#8217;s because there is nothing else that needs to<br \/>\nhappen.<\/p>\n<p>When this function returns, the built-in message loop resumes. If there is<br \/>\nnothing to do, the message loop blocks on the <b>GetMessage<\/b>, thus not<br \/>\nconsuming any CPU cycles because there is nothing else to do. In the best case,<br \/>\nif this were the only application requiring service on the CPU, 100% of the CPU<br \/>\ncycles would go to accomplishing useful work in the thread, instead of 50% to a<br \/>\nuseless <b>PeekMessage<\/b> loop and 50% to the thread. Read: if your task took<br \/>\nten minutes under the previous implementation, it takes five minutes under this<br \/>\none. That performance improvement matters.<\/p>\n<p>Now what does the thread function look like? For details, consult my <a href=\"workerthreads.htm\">essay<br \/>\non worker threads<\/a>, but the code is simply expressed as<\/p>\n<pre>\/* static *\/ UINT CMyWndClass::threadfunc(LPVOID p)\r\n   {\r\n     ((CMyWndClass *)p)-&gt;RunThread();\r\n     return 0; \/\/ return value never, ever is of interest\r\n   }\r\n\r\nvoid CMyWndClass::threadfunc()\r\n   {\r\n    while(running)\r\n      { \/* thread loop *\/\r\n       ...do thread thing here...\r\n       if(thread_has_completed_its_work)\r\n         break;\r\n      } \/* thread loop *\/\r\n    PostMessage(UWM_THREAD_FINISHED); \/\/ See my <a href=\"messages.htm\">essay on Message Management<\/a>\r\n\r\n   }\r\n\r\nLRESULT CMyWndClass::OnThreadFinished(WPARAM, LPARAM)\r\n   {\r\n    DoSomething();\r\n    running = FALSE;\r\n    updateControls(); \/\/ dialogs only\r\n    return 0;\r\n   }<\/pre>\n<p>This is not only efficient, but note that it does not do any synchronization!<br \/>\nWhy not? Clearly, the <b>running<\/b> flag is being accessed by two different<br \/>\nthreads: the GUI-level thread can set it to <b>FALSE<\/b> by the user clicking a <b>Stop<\/b><br \/>\nbutton or selecting a <b>Stop<\/b> menu item or any other of a variety of ways.<br \/>\nSo why don&#8217;t we need synchronization?<\/p>\n<p><a name=\"Synchronization is needed\">Synchronization is needed<\/a> only when<br \/>\nconcurrent access can produce incorrect results. The main GUI thread never reads<br \/>\nthe value; it only writes it. The worker thread only reads it, but if there is<br \/>\nany timing error it really doesn&#8217;t matter in the slightest. The worst case is<br \/>\nthat the worker thread might go through the loop one more time if there was a<br \/>\nconcurrent access that caused the thread to see a <b>TRUE<\/b> although<br \/>\nconcurrently there was a <b>FALSE<\/b> being set. So functionally, this is the<br \/>\nsame as if the user had hesitated perhaps an extra nanosecond on the click. So<br \/>\nno synchronization is required.<\/p>\n<p>What about the argument that &quot;I don&#8217;t want the user to start the<br \/>\nthread(s) again until it(they) finish&quot;. Well, the first example code<br \/>\ndoesn&#8217;t actually prevent that from happening! So it would be possible to start a<br \/>\nnew of thread running each time the operation was re-selected. You need some way<br \/>\nto disable the initiation of new threads. The simplest way to do this in a<br \/>\nview-based app that is using menu items or toolbar buttons is to simply have an <b>UPDATE_COMMAND_UI<\/b><br \/>\nhandler:<\/p>\n<pre>void CMyView::OnUpdateStartThreads(CCmdUI * pCmdUI)\r\n   {\r\n     pCmdUI-&gt;Enable(!running);\r\n   }<\/pre>\n<p>The controls are disabled if the thread is running. For a dialog, or a <b>CFormView<\/b>,<br \/>\nwhere you have a button on the dialog or form, the <b>updateControls<\/b> handler<br \/>\nI describe in my <a href=\"controls.htm\">essay on control management<\/a> would be<\/p>\n<pre>void CMyDialog::updateControls()\r\n   {\r\n    ...other stuff here\r\n    c_StartThread.EnableWindow(!running);\r\n   }<\/pre>\n<p>Note how much simpler the code is. There are no temporal dependencies that<br \/>\nare enforced by syntactic sequencing. The system is fully asynchronous, requires<br \/>\na minimum of synchronization (none), consumes no CPU cycles by polling for<br \/>\nmessages, and is easier to understand.<\/p>\n<hr>\n<h3><a name=\"volatile\">Failure to use volatile<\/a><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">potentially fatal<\/a><\/p>\n<p>Any variable that is shred between two threads and can be changed<br \/>\nconcurrently <i>must<\/i> be marked as <b>volatile<\/b>. This keeps the compiler<br \/>\nfrom doing certain optimizations, such as code motions, constant propagation and<br \/>\ncommon subexpression elimination, on a variable whose value might change<br \/>\nspontaneously.<\/p>\n<p>Note that declare a variable as <b>volatile <\/b>does <i>not<\/i> make it<br \/>\nthread-safe. But a thread-safe variable, properly handled with synchronization<br \/>\nprimitives, can <i>still<\/i> produce incorrect results in the Release version if<br \/>\nthe variable is not declared <b>volatile<\/b>.<\/p>\n<p>Example:<\/p>\n<pre>while(running)\r\n    { \/* thread loop *\/\r\n     ...bunch of stuff here\r\n    } \/* thread loop *\/<\/pre>\n<p>looks like a perfectly good loop, where <b>running<\/b> is, for example, a<br \/>\nmember variable of a class and can be modified by some other thread. For<br \/>\nexample, you might do<\/p>\n<pre>void CMyDialog::OnCancel()\r\n   {\r\n    thread-&gt;running = FALSE;\r\n   }<\/pre>\n<p>However, the optimizing compiler might detect that within the thread loop,<br \/>\nnothing modifies the <b>running<\/b> variable. If it believes this, it feels<br \/>\nperfectly free to transform the program <i>as if it had been coded<\/i><\/p>\n<pre>if(running)\r\n   { \/* thread loop *\/\r\n     compiler_generated_label:\r\n       ...bunch of stuff here\r\n     goto compiler_generated_label;\r\n    } \/* thread loop *\/<\/pre>\n<p>Now, you say, that&#8217;s ridiculous! That&#8217;s a completely different program! Not<br \/>\nso. From the viewpoint of code optimization the two programs are <i>absolutely<br \/>\nidentical<\/i>. This is because the optimizer assumes single-thread semantics.<br \/>\nAnd this assumption is completely wrong.<\/p>\n<p>If, however, you declared the member variable as<\/p>\n<pre><b>volatile<\/b> BOOL running;<\/pre>\n<p>then the compiler recognizes that some mechanism it is not aware of can<br \/>\nchange the value, and it will not do the transformation.&nbsp;<\/p>\n<hr>\n<h3><a name=\"Synchronization\">Failure to synchronize access to a variable<br \/>\nbetween threads<\/a><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">potentially fatal<\/a><\/p>\n<p>No variable or structure should be accessed from multiple threads without<br \/>\nbeing accessed in a thread-safe fashion. Note that any thread-safe access must<br \/>\nalso be multiprocessor-safe.&nbsp;<\/p>\n<p>Note that this applies only to variables where concurrent access can produce<br \/>\nincorrect results. There are situations in which concurrent access can never<br \/>\nresult in an incorrect result. <a href=\"#Synchronization is needed\">One such<br \/>\nexample<\/a> is discussed in this essay in the <a href=\"#Using PeekMessage anywhere\">section<br \/>\non the (mis)use of <b>PeekMessage<\/b><\/a><b>.<\/b><\/p>\n<p>However, for situations in which concurrent access can produce an incorrect<br \/>\nresult, you <i>must<\/i> provide proper synchronization. This means that even trivial actions like<\/p>\n<pre><b>volatile<\/b> int a;<\/pre>\n<pre>a++; \/\/ not safe!<\/pre>\n<p>cannot possibly work. If you look at the generated code, you will find that<br \/>\nit actually takes a couple instructions to increment a, but even if the compiler<br \/>\ngenerated an <b>inc<\/b> instruction, that takes <i>two memory cycles<\/i>, which<br \/>\nmeans that in a multiprocessor environment the other processor could<br \/>\nsimultaneously fetch the initial value. Then both processors would increment the<br \/>\nvalue (say, from 17 to 18) and the value 18 would be stored back, first by one<br \/>\nprocessor, then by the other. So executing a++ twice would cause the value to go<br \/>\nfrom 17 to 18, which doesn&#8217;t make much sense.<\/p>\n<p>If you believe this cannot happen, you are wrong. I first found this in an<br \/>\noperating system in 1968. I found that instead of doing the multithread-safe<br \/>\nincrement, it did a multithread-unsafe increment. I reported this to my manager,<br \/>\nwho reported it to IBM. In addition I fixed it. Suddenly, the MTBF of the system<br \/>\nwent up; in retrospect, examining the &quot;indeterminate&quot; crash memory<br \/>\ndumps, we determined that one crash a week happened because there was a thread<br \/>\npreemption between the instruction that tested the value and the instruction<br \/>\nthat set the value.<\/p>\n<p>For simple operations, like increment, decrement, simple addition and<br \/>\nsubtraction, and a compare-and-exchange, there are <b>Interlocked&#8230;<\/b><br \/>\noperations, so the correct form of the code would be<\/p>\n<pre><b>volatile <\/b>long a;<\/pre>\n<pre>InterlockedIncrement(&amp;a);<\/pre>\n<p>There are also <b>InterlockedDecrement<\/b>, <b>InterlockedExchangeAdd<\/b>,<br \/>\nand <b>InterlockedCompareAndExchange<\/b>, among others.<\/p>\n<p>However, generally you need to provide higher-level synchronization on<br \/>\nobjects, because very few changes can take place in a single instruction. So you<br \/>\nshould use <b>CRITICAL_SECTION<\/b> or a Mutex, or the MFC classes <b>CCriticalSection<\/b><br \/>\nor <b>CMutex<\/b> to provide the necessary synchronization.<\/p>\n<p>There is a persistent piece of misinformation which I have said back to me<br \/>\noften enough to have realized this has now achieved the status of Programming<br \/>\nLegend: by declaring a variable as <b>volatile<i> <\/i><\/b>access to it is<br \/>\nimplicitly synchronized. Nothing could be further from the truth. The truth is<br \/>\nthat <b>volatile<\/b> in <i>no way<\/i> provides synchronization. What it does do<br \/>\nis inform the other threads that they cannot cache the value, which is not at<br \/>\nall the same! There is absolutely, positively, no synchronization whatsoever<br \/>\nprovided by declaring a variable as <b>volatile<\/b>. You, and you alone, are<br \/>\nresponsible for providing synchronization. If, however, you also fail to declare<br \/>\nthe variable as <b>volatile<\/b>, the cached value may be used by another thread,<br \/>\nwhich would also be incorrect. You must do both.<\/p>\n<p>See my companion essay on <a href=\"semaphores.htm\">synchronization<\/a>.<\/p>\n<hr>\n<h3><a name=\"Overriding the Run() method in a CWinThread class\">Overriding the<br \/>\n<b>Run()<\/b> method in a <b>CWinThread<\/b> class<\/a><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">fatal<\/a>. No &quot;potentially&quot; about it.<br \/>\nPrograms that are written this way invariably do not even work, from day one.<\/p>\n<p>Basically, there is no reason to do this. Or the reasons are so exotic that<br \/>\nyou have to be a very advanced user to do this sanely.<\/p>\n<p>Hint: I&#8217;ve been writing threaded code for over a decade and not once, not<br \/>\never, have I had a need to override the <b>Run()<\/b> method.<\/p>\n<p>Invariably this is the result of a misunderstanding of the purpose of a UI<br \/>\nthread.<\/p>\n<p>The purpose of a UI thread is to have a message pump running. This is<br \/>\nimportant for dispatching events such as socket messages and other asynchronous<br \/>\nevents from libraries such as SAPI (the speech API). Overriding the <b>Run<\/b><br \/>\nmethod will block these messages. The most common failure mode is to put an<br \/>\ninfinite loop in the <b>Run()<\/b> method. This can be assumed to make no sense.<br \/>\nIf you need an infinite loop, use a general worker thread. If you need a UI<br \/>\nthread, you do not need an infinite loop in it.<\/p>\n<p>Whatever you are trying to do, overriding <b>Run<i> <\/i><\/b>is going to be<br \/>\nthe wrong way to accomplish it. Putting an infinite loop in the <b>Run<\/b><br \/>\nmethod is always a mistake.<\/p>\n<hr>\n<h3>\n<a name=\"Putting an infinite loop in the InitInstance handler of a UI thread\"><br \/>\nPutting an infinite loop in the InitInstance handler of a UI thread<\/a><\/h3>\n<p>This makes no sense at all. Ever.<\/p>\n<p>It defeats the purpose of having a UI thread. There is absolutely no way this<br \/>\ncould ever make sense in a UI thread. Use a worker thread. It will block the<br \/>\nmessage pump, which is the only reason you would ever need a UI thread.<br \/>\nTherefore it represents a fundamental design flaw. <\/p>\n<p>Whatever was intended by this, the choice of putting it in a UI thread is<br \/>\nalways a mistake.<\/p>\n<hr>\n<h3><a name=\"SendMessage\">SendMessage between threads<\/a><\/h3>\n<p>Severity: <a href=\"#Serious\">serious<\/a>, <a href=\"#Potentially fatal\"><br \/>\npotentially fatal<\/a><\/p>\n<p>Never use <b>SendMessage<\/b> between threads. The result of this can be a<br \/>\ndeadlock situation. The deadlock can be unpredictable and therefore difficult to<br \/>\ndebug if it appears to be happening. So the easiest way to avoid this is to<br \/>\nnever use it.<\/p>\n<p>Use <b>PostMessage<\/b> to send messages between threads. This also means that<br \/>\na worker thread cannot use most methods on controls, since they all end up being<\/p>\n<p><b>SendMessage<\/b> calls. Here are just a <i>few<\/i> of the operations you must <i>not<\/i><br \/>\ndo on a control or window from a thread which does not own it. I don&#8217;t intend to<br \/>\nreproduce the entire list here. Assume that if you are doing <i>anything<\/i> to<br \/>\na window (or a control, which is just a window) from a thread, <i>except<\/i> <b>PostMessage<\/b>,<br \/>\nyour program is at serious risk.<\/p>\n<p>Note that I&#8217;ve had people say &quot;But I&#8217;m not sending <i>any<\/i> messages<br \/>\nto the controls; I use MFC methods!&quot; which is actually the same as saying<br \/>\n&quot;I send messages to controls&quot;. MFC is just a nice syntactic wrapper on<br \/>\nhundreds of <b>SendMessage<\/b> operations.<\/p>\n<table border=\"1\" width=\"100%\" height=\"1\">\n<tr>\n<td width=\"33%\" height=\"19\"><b><i>Message prefix<\/i><\/b><\/td>\n<td width=\"33%\" height=\"19\"><b><i>Example messages<\/i><\/b><\/td>\n<td width=\"34%\" height=\"19\"><b><i>MFC equivalents<\/i><\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" rowspan=\"2\" height=\"44\"><font face=\"Arial\"><b>BM_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>BM_GETCHECK<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CButton::GetCheck<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>BM_SETCHECK<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CButton::SetCheck<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" rowspan=\"4\" height=\"94\"><font face=\"Arial\"><b>CB_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>CB_ADDSTRING<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CComboBox::AddString<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>CB_DELETESTRING<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CComboBox::DeleteString<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>CB_FINDSTRING<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CComboBox::FindString<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>CB_GETCOUNT<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CComboBox::GetCount<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" rowspan=\"3\" height=\"69\"><font face=\"Arial\"><b>CBEM_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>CBEM_DELETEITEM<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CComboBoxEx::DeleteItem<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>CBEM_GETITEM<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CComboBoxEx::GetItem<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>CBEM_INSERTITEM<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CComboBoxEx::InsertItem<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" rowspan=\"2\" height=\"44\"><font face=\"Arial\"><b>DM_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>DM_GETDEFID<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CDialog::GetDefID<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>DM_SETDEFID<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CDialog::SetDefID<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" rowspan=\"3\" height=\"69\"><font face=\"Arial\"><b>DTM_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"19\"><b><font face=\"Arial\">DTM_GETRANGE<\/font><\/b><\/td>\n<td width=\"34%\" height=\"19\"><b>CDateTimeCtrl::GetRange<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><b><font face=\"Arial\">DTM_GETSYSTEMTIME<\/font><\/b><\/td>\n<td width=\"34%\" height=\"19\"><b>CDateTimeCtrl::GetSystemTime<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><b><font face=\"Arial\">DTM_SETRANGE<\/font><\/b><\/td>\n<td width=\"34%\" height=\"19\"><b>CDateTimeCtrl::GetRange<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" rowspan=\"3\" height=\"69\"><font face=\"Arial\"><b>EM_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>EM_GETLIMITTEXT<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CEdit::GetLimitText<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>EM_GETLINE<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CEdit::GetLine<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>EM_GETLINECOUNT<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CEdit::GetLineCount<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" rowspan=\"4\" height=\"94\"><font face=\"Arial\"><b>HDM_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"19\"><b><font face=\"Arial\">HDM_DELETEITEM<\/font><\/b><\/td>\n<td width=\"34%\" height=\"19\"><b>CHeaderCtrl::DeleteItem<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><b><font face=\"Arial\">HDM_GETITEM<\/font><\/b><\/td>\n<td width=\"34%\" height=\"19\"><b>CHeaderCtrl::GetItem<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><b><font face=\"Arial\">HDM_INSERTITEM<\/font><\/b><\/td>\n<td width=\"34%\" height=\"19\"><b>CHeaderCtrl::InsertItem<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><b><font face=\"Arial\">HDM_SETITEM<\/font><\/b><\/td>\n<td width=\"34%\" height=\"19\"><b>CHeaderCtrl::SetItem<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"73\" rowspan=\"4\"><font face=\"Arial\"><b>IPM_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"16\"><b><font face=\"Arial\">IPM_CLEARADDRESS<\/font><\/b><\/td>\n<td width=\"34%\" height=\"16\"><b>CIPAddressCtrl::ClearAddress<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><b><font face=\"Arial\">IPM_GETADDRESS<\/font><\/b><\/td>\n<td width=\"34%\" height=\"19\"><b>CIPAddressCtrl::GetAddress<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><b><font face=\"Arial\">IPM_ISBLANK<\/font><\/b><\/td>\n<td width=\"34%\" height=\"19\"><b>CIPAddressCtrl::IsBlank<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><b><font face=\"Arial\">IPM_SETADDRESS<\/font><\/b><\/td>\n<td width=\"34%\" height=\"19\"><b>CIPAddressCtrl::SetAddress<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" rowspan=\"4\" height=\"94\"><font face=\"Arial\"><b>LB_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>LB_ADDSTRING<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CListBox::AddString<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>LB_DELETESTRING<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CListBox::DeleteString<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>LB_GETCURSEL<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CListBox::GetCurSel<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>LB_SETCURSEL<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CListBox::SetCurSel<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"57\" rowspan=\"3\"><font face=\"Arial\"><b>LVM_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">LVM_DELETEITEM<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CListCtrl::DeleteItem<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">LVM_EDITLABEL<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CListCtrl::EditLabel<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">LVM_GETITEM<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CListCtrl::GetItem<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"57\" rowspan=\"3\"><font face=\"Arial\"><b>MCM_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">MCM_GETCURSEL<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CMonthCalCtrl::GetCurSel<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">MCM_GETMONTHRANGE<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CMonthCalCtrl::GetMonthRange<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">MCM_SETRANGE<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CMonthCalCtrl::SetRange<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"57\" rowspan=\"3\"><font face=\"Arial\"><b>PBM_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">PBM_GETPOS<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CProgessCtrl::GetPos<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">PBM_SETRANGE32<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CProgressCtrl::SetRange32<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">PBM_STEPIT<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CProgressCtrl::Stepit<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"57\" rowspan=\"3\"><font face=\"Arial\"><b>PSM_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">PSM_ADDPAGE<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CPropertySheet::AddPage<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">PSM_GETPAGEINDEX<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CPropertySheet::GetPageIndex<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">PSM_GETACTIVEPAGE<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CPropertySheet::GetActivePage<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"57\" rowspan=\"3\"><font face=\"Arial\"><b>RB_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">RB_GETBANDCOUNT<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CRebarCtrl::GetBandCount<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">RB_GETBKCOLOR<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CRebarCtrl::GetBkColor<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">RB_SETBANDINFO<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CRebarCtrl::SetBandInfo<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"78\" rowspan=\"4\"><font face=\"Arial\"><b>SB_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"4\" rowspan=\"2\"><b><font face=\"Arial\">SB_GETTEXT<\/font><\/b><\/td>\n<td width=\"34%\" height=\"3\"><b>CStatusBar::GetPaneText<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"34%\" height=\"1\"><b>CStatusBarCtrl::GetText<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"2\" rowspan=\"2\"><b><font face=\"Arial\">SB_SETTEXT<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CStatusBar::SetPaneText<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"34%\" height=\"1\"><b>CStatusBarCtrl::SetText<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" rowspan=\"3\" height=\"69\"><font face=\"Arial\"><b>SBM_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>SBM_GETPOS<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CScrollBar::GetPos<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>SBM_SETPOS<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CScrollBar::SetPos<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>SBM_SETRANGE<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CScrollBar::SetRange<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" rowspan=\"4\" height=\"94\"><font face=\"Arial\"><b>STM_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>STM_GETICON<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CStatic::GetIcon<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>STM_GETIMAGE<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CStatic::GetImage<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>STM_SETICON<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CStatic::SetIcon<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"19\"><font face=\"Arial\"><b>STM_SETIMAGE<\/b><\/font><\/td>\n<td width=\"34%\" height=\"19\"><b>CStatic::SetImage<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"57\" rowspan=\"3\"><font face=\"Arial\"><b>TB_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">TB_ISBUTTONENABLED<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CToolbarCtrl::IsButtonEnabled<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">TB_PRESSBUTTON<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CToolbarCtrl::PressButton<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">TB_SETSTATE<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CToolBarCtrl::SetState<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"57\" rowspan=\"3\"><b><font face=\"Arial\">TBM_<\/font><\/b><\/td>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">TBM_CLEARSEL<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CSliderCtrl::ClearSel<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">TBM_GETNUMTICS<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CSliderCtrl::GetNumTics<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">TBM_SETBUDDY<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CSliderCtrl::SetBuddy<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"57\" rowspan=\"3\"><font face=\"Arial\"><b>TCM_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">TCM_ADJUSTRECT<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CTabCtrl::AdjustRect<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">TCM_GETITEM<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CTabCtrl::GetItem<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">TCM_SETIMAGELIST<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CTabCtrl::SetImageList<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"57\" rowspan=\"3\"><font face=\"Arial\"><b>TTM_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"1\"><font face=\"Arial\"><b>TTM_ADDTOOL<\/b><\/font><\/td>\n<td width=\"34%\" height=\"1\"><b>CToolTipCtrl::AddTool<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><font face=\"Arial\"><b>TTM_GETTOOLINFO<\/b><\/font><\/td>\n<td width=\"34%\" height=\"1\"><b>CToolTipCtrl::GetToolInfo<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><font face=\"Arial\"><b>TTM_<font color=\"#FF0000\">NEW<\/font>TOOLRECT<\/b><\/font><\/td>\n<td width=\"34%\" height=\"1\"><b>CToolTipCtrl::<font color=\"#FF0000\">Set<\/font>ToolRect<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"57\" rowspan=\"3\"><font face=\"Arial\"><b>TVM_<\/b><\/font><\/td>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">TVM_DELETEITEM<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CTreeCtrl::DeleteItem<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">TVM_GETCOUNT<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CTreeCtrl::GetCount<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">TVM_GETITEMRECT<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CTreeCtrl::GetItemRect<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"38\" rowspan=\"2\"><b><font face=\"Arial\">UDM_<\/font><\/b><\/td>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">UDM_GETBUDDY<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CSpinCtrl::GetBuddy<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"33%\" height=\"1\"><b><font face=\"Arial\">UDM_SETRANGE32<\/font><\/b><\/td>\n<td width=\"34%\" height=\"1\"><b>CSpinCtrl::SetRange32<\/b><\/td>\n<\/tr>\n<\/table>\n<hr>\n<h3><a name=\"Believing a thread starts immediately\">Believing a thread starts<br \/>\nimmediately<\/a>\/Believing a thread does <i>not<\/i> start immediately<\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">potentially fatal<\/a><\/p>\n<p>Rule 1: any time you assume that a non-suspended thread starts immediately,<br \/>\nyou are wrong<br \/>\nRule 2: any time you assume there is a delay in starting a non-suspended thread,<br \/>\nyou are wrong<br \/>\nRule 3: there are no exceptions for non-suspended threads. See rules 1 and 2.<\/p>\n<p>An example of the first failure is seen by the number of people who pass a<br \/>\nlocal variable to a thread:<\/p>\n<pre>SOMESTRUCT s;\r\ns.whatever = somevalue;\r\ns.thing = something;\r\nAfxBeginThread(threadfunc, &amp;s);<\/pre>\n<p>The first failure is that the code will be something like<\/p>\n<pre>UINT threadfunc(LPVOID p)\r\n    SOMESTRUCT * s = (SOMESTRUCT *)p;\r\n    ...stuff\r\n    ... = s-&gt;whatever; \/\/ invalid access<\/pre>\n<p>By the time the thread gets around to accessing the <b>s-&gt;whatever<\/b> field,<br \/>\nthe struct is long gone. The creating function returned, its stack frame is<br \/>\ngone, and the space formerly used to hold <b>SOMESTRUCT&nbsp;s<\/b> is now being used<br \/>\nfor some other purpose. It gets even worse if the contents of <b>SOMESTRUCT<\/b> <\/p>\n<p>were pointers; they now point to <i>someplace<\/i>, but where? Who knows?<br \/>\nCertainly serious malfunctions will result if they are used to load or store<br \/>\nanything.<\/p>\n<p>I&#8217;ve seen a solution posted that looked like this: <\/p>\n<pre>UINT threadfunct(LPVOID p)\r\n   {\r\n     SOMESTRUCT s = *(SOMESTRUCT *)p;<\/pre>\n<p>and the explanation was that by making a copy, the contents would now be<br \/>\nsaved. Sorry to disappoint the poster, but this is every bit as incorrect as the<br \/>\nprevious example, and for the same reasons. All you know about a thread, once<br \/>\nyou&#8217;ve called the <b>::CreateThread<\/b> call (by whatever wrapper your<br \/>\nenvironment demands, such as <b>_beginthread<\/b>, <b>_beginthreadex<\/b>, or one<br \/>\nof the forms of <b>AfxBeginThread<\/b>), is that <i>at some point in the<br \/>\nindeterminate future, the thread will start<b>. And at some other indefinite<br \/>\npoint in the future, the thread will end<\/b>.<\/i><\/p>\n<p>If you need to pass information across a thread boundary, it must be space<br \/>\nthat is either statically allocated, or is allocated on the heap, and it must be<br \/>\nguaranteed to <i>remain correct for the entire lifetime of the thread<\/i>.<br \/>\nAnything less will not work. <\/p>\n<p>Sometimes you have a single thread that does one thing. In this case, it<br \/>\nsometimes can simply use member variables of the class that spawns it. For<br \/>\nexample, a thread started by a <b>CView<\/b>-derived or <b>CDialog<\/b>-derived<br \/>\nclass may use member variables of the class instance. Note that it is your<br \/>\nresponsibility to see that this thread has completely terminated before allowing<br \/>\nthe <b>CView<\/b> or <b>CDialog <\/b>to be destroyed. Rather than use individual<br \/>\nmembers, it is often best to have a struct\/class which contains all the<br \/>\nvariables needed for the thread.<\/p>\n<p>Sometimes you need many threads to do certain tasks on behalf of a single<br \/>\nview, document, or other class. In this case, it would be impossible to use a<br \/>\nsingle variable or set of variables to hold the state. In this case, you must<br \/>\nactually allocate heap memory and pass a pointer to this heap memory to your<br \/>\nthread. The memory must be freed by the thread when it has finished using it.<\/p>\n<p>The complementary problem is the illusion that the thread still exists after<br \/>\nthe return from <b>::CreateThread<\/b> or its wrappers. For example, here is a<br \/>\nclassic error:<\/p>\n<pre>CMyThread * t = (CMyThread *)AfxBeginThread(RUNTIME_CLASS(CMyThread), ...);\r\nt-&gt;m_bAutoDelete = FALSE;<\/pre>\n<p>Whoops! If you think this code can work, rethink what you are doing. It<br \/>\ncannot work. By the time the assignment is done to <b>t<\/b>, the thread might<br \/>\nhave finished, and because <b>m_bAutoDelete<\/b> was implicitly <b>TRUE<\/b> to<br \/>\nstart, the thread object referred to by <b>t<\/b> is gone, it has been returned<br \/>\nto the heap, the space has been reallocated for some other purpose, and you just<br \/>\nstored the value &quot;1&quot; <i>somewhere<\/i>, but you have no idea where! Perhaps you<br \/>\nmerely corrupted the heap. Perhaps you have damaged some other data structure.<br \/>\nYou have no idea. None whatsoever. And someday your code is going to crash and<br \/>\nburn in a spectacular manner.<\/p>\n<p>This is one of the many reasons that keeping thread object pointers around<br \/>\nbeyond the immediate creation of the thread is often useless. If you need to set<br \/>\nmember variables, you need to do<\/p>\n<pre>CMyThread * t = (CMyThread *)AfxBeginThread(RUNTIME_CLASS(CMyThread), ..., CREATE_SUSPENDED, ...);\r\nt-&gt;m_bAutoDelete = FALSE;\r\nt-&gt;anythingelse = something;\r\nt-&gt;ResumeThread();<\/pre>\n<p><i>Now<\/i> you can depend on the fact that the thread has not started<br \/>\nrunning, because it was created suspended. Until you execute <b>ResumeThread<\/b>,<br \/>\nyou are safe. Once <b>ResumeThread<\/b> is called, the thread could be terminated<br \/>\nbefore the call returns. (and if you think this is impossible, you have not<br \/>\nthought out what threading means).<\/p>\n<p>One of the common questions which arises under these conditions is &quot;But I<br \/>\ncan&#8217;t do <i>x<\/i> until I know the thread is executing!&quot;. If that is so, you<br \/>\nneed to rethink what you are doing. If you need to do <i>w<\/i>, start a thread,<br \/>\nwait for the thread to be running, and then do <i>x<\/i>, you have to stop<br \/>\nthinking in a procedural fashion and think in an event-driven fashion. The<br \/>\ncorrect approach is to do <i>w<\/i>, and start the thread. That&#8217;s it. That&#8217;s as<br \/>\nfar as you go. If <i>x<\/i> needs to be done after the thread starts, why is it<br \/>\nnot done <i>in the thread?<\/i> That&#8217;s the first question to ask. If there is<br \/>\nactually a good reason (not just a failure in design) that this must be so, then<br \/>\nthe correct behavior is to have the thread <b>PostMessage<\/b> a notification to<br \/>\nthe main GUI thread, or possibly <b>PostThreadMessage<\/b> if it was spawned by<br \/>\nsome other UI thread, and when that message is received, you are now free to do<\/p>\n<p><i>x<\/i>.<\/p>\n<p>I&#8217;ve seen solutions of the form:<\/p>\n<pre>HANDLE h = ::CreateEvent(NULL, TRUE, FALSE, NULL);\r\nAfxBeginThread(threadfunc, (LPVOID)h);\r\n::WaitForSingleObject(h, INFINITE);<\/pre>\n<p>where the thread contains<\/p>\n<pre>UINT threadfunc(LPVOID p)\r\n    {\r\n     HANDLE h = (HANDLE)p;\r\n     ... thread setup goes here...\r\n     ::SetEvent(h);\r\n     ... rest of thread goes here...\r\n    }<\/pre>\n<p>which is a bit clunky; it is not a clean solution. Worse still, I&#8217;ve seen the<br \/>\npassing of two event handles; after the creator comes out of the <b><br \/>\n::WaitForSingleObject<\/b>, it then does something and does a <b>::SetEvent<\/b> <\/p>\n<p>to tell the thread it can now continue; the thread, after it did the <b>::SetEvent<\/b><br \/>\nto resume its creator, did a <b>::WaitForSingleObject<\/b> to wait for a resume<br \/>\nnotification. This is <i>really<\/i> clumsy, and shows a failure to give up<br \/>\nprocedural, sequential thought models. Junk code like this, and rewrite it into<br \/>\nsomething simple. Nearly all the time I see code like this, there is actually a<br \/>\nmuch simpler way to write it. The few times a better solution was not feasible,<br \/>\nit was because of fundamental design failures elsewhere that could not be easily<br \/>\nrewritten. Poor design is poor design, and there is usually not a single point<br \/>\nwhere it goes bad, but <i>lots<\/i> of places that go bad.<\/p>\n<hr>\n<h3><b><a name=\"ExitProcess\">ExitProcess() and exit()<\/a><\/b><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">potentially fatal<\/a><\/p>\n<p>Programmers have been erroneously trained to &quot;exit the program if there<br \/>\nis an error&quot;. Much of this training was simply incorrect, and was often<br \/>\nbased upon people who learned how to program when programs were encoded in<br \/>\npieces of cardboard and run overnight.<\/p>\n<p>In a modern interactive program it is <i>never<\/i> appropriate to &quot;exit<br \/>\nthe program&quot;. Exiting the program is an admission of total failure. It is<br \/>\nalways an error. Therefore, an <b>ExitProcess<\/b> call, or as it is disguised by<br \/>\nthe C library, <b>exit<\/b>, is always inappropriate. If you think you have an<\/p>\n<p>&quot;unrecoverable error&quot;, you are wrong. <i>All<\/i> errors are<br \/>\nrecoverable. The recovery may mean that a whole lot of menu items, controls,<br \/>\netc. are now disabled, but the condition is <i>always<\/i> recoverable with<br \/>\nrespect to keeping the program running. To think that such a thing as an &quot;urecoverable&quot;<br \/>\nerror that necessitates exiting the program could ever exist is a deep flaw in<br \/>\nthinking.<\/p>\n<p>I once bought a third party database library, <b>CodeBase<\/b>. It was without<br \/>\na doubt the <i>worst<\/i> subroutine library I have had the misfortune to be<br \/>\nsubjected to. Its attitude was that if an error occurred, there were two errors:<br \/>\nthose caused by incorrect programming, which would pop up and obscenely cryptic <b>MessageBox<\/b>,<\/p>\n<p><i>underneath the application<b> <\/b><\/i>because the programmer did not<br \/>\nunderstand that using a <b>NULL<\/b> handle made the dialog box a child of the<br \/>\ndesktop, and those errors which were caused by its perception that data was<br \/>\nincorrect, in which case it called <b>exit<\/b> instead of returning an error<br \/>\ncode that said &quot;data corrupted&quot;. They would not even listen to an<br \/>\nanalysis of what was wrong; they gave lame excuses such as &quot;If the index is<br \/>\nbad, we can&#8217;t proceed&quot;. Fine, <i>but that has nothing to do with the<br \/>\nprogram<\/i>. Any subroutine library that contains an <b>ExitProcess<\/b> or <b>exit<\/b><\/p>\n<p>is so fundamentally erroneous that it can only be ignored as a piece of<br \/>\nlegitimate software. Its inclusion in a project probably dooms the project.<br \/>\nAfter all, do <i>you<\/i> want to take the call from your customer saying &quot;I<br \/>\nwas working in the program and it just went away!&quot;? Do you think you can<br \/>\nreproduce it?<\/p>\n<p>The arrogance that says a subroutine writer has the right to determine that<br \/>\nmy program should shut down requires a serious attitude adjustment on the part<br \/>\nof that programmer. No subroutine has the right to terminate a program. Only the<br \/>\nuser has the right to terminate a program. Now, the user may choose to do so<br \/>\nbecause an internal error has rendered the program unusable, but by that time,<br \/>\nthere should have been detailed analyses of the failure mode presented to the<br \/>\nuser, the error would have been logged in a way that can be presented to a<br \/>\ntechnical support person, and operations the user might do that would now be<br \/>\ninvalid should be disabled.<\/p>\n<p>So you say, &quot;If that error occurs, the user cannot proceed!&quot;. Fine. This<br \/>\nmeans you end up disabling all the menu items and toolbar items except those<br \/>\nwhich are still viable, such as <b>Exit<\/b> and <b>About&#8230;<\/b> (the latter is<br \/>\ncritical if the user calls tech support!)<\/p>\n<p>If an error occurs in a subroutine, return an error code. Or throw an<br \/>\nexception. But never, ever call <b>ExitProcess<\/b>. In addition, in a GUI<br \/>\nprogram, if you call <b>ExitProcess<\/b>, the process stops. The user gets no<br \/>\nchance to decide if buffers should be saved; the mechanism that asks the<br \/>\nquestion has been bypassed; objects which may need to be cleaned up (for<br \/>\nexample, semaphores, which have an existence independent of the process itself)<br \/>\nare left corrupted; Mutexes which are currently locked will generate <b>WAIT_ABANDONED<\/b><br \/>\nnotifications, which guarantee that other processes which are depending on them<br \/>\nwill also have to enter a nonrecoverable error situation; data which has been<br \/>\nbuffered but not yet written to the kernel, such as file buffers and record<br \/>\nbuffers, are lost. Because of these hazards, I have classified this as <b><a href=\"#Potentially fatal\">potentially<br \/>\nfatal<\/a><\/b>.<\/p>\n<p>It doesn&#8217;t matter what you need to do to avoid <b>ExitProcess<\/b>. Do it. It<br \/>\ndoesn&#8217;t matter if the program is a GUI program or an ordinary console app; <i>never<\/i><br \/>\ncall <b>ExitProcess<\/b> (or <b>exit<\/b>). I have managed to avoid using this<br \/>\n(except for the occasional trivial ten-line test program, and even then I get<br \/>\nnervous) for something like 20 years. It isn&#8217;t hard.<\/p>\n<hr>\n<h3><a name=\"PostQuitMessage\">PostQuitMessage() and PostMessage(WM_QUIT)<\/a><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">potentially fatal<\/a>. If you are<br \/>\nlucky, merely <a href=\"#SendMessage\">serious<\/a><\/p>\n<p>Using these on the main GUI thread is almost always an error. The <i>only<\/i><br \/>\ncontext in which they ever made sense was in the <b>WM_DESTROY<\/b> (or the <b>WM_NCDESTROY<\/b>)<br \/>\nhandler of a pure C API program. They never made sense in any other context in<br \/>\npure C programming, and they <i>never<\/i> make sense in an MFC program.<\/p>\n<p>The way to shut a program down is to <b>PostMessage(WM_CLOSE)<\/b> to the main<br \/>\nwindow. This invokes the standard closedown actions, which typically include<br \/>\nsuch actions as prompting the user to save unsaved buffers. If you get a <b>WM_QUIT<\/b><br \/>\nmessage to the message loop, the message loop shuts down <i>immediately<\/i> and<br \/>\ncontrol proceeds to <b>ExitInstance<\/b>. Nothing else in the program associated<br \/>\nwith shutdown will take place. This will eventually lead to fatal situations; if<br \/>\nnot immediately, certainly later (often before the product is released, and if<br \/>\nnot then, usually on the first round of maintenance).&nbsp;<\/p>\n<p>The only valid place these can make sense is to shut down a worker thread<br \/>\nwith a message queue, known somewhat erroneously as a &quot;UI&quot; thread, and<br \/>\nthen only if you have a fair degree of confidence that everything else in the<br \/>\nthread is shut down. Usually I will <b>PostMessage<\/b> a message to the UI<br \/>\nthread asking it to shut itself down, and when it has determined it is in a<br \/>\nclean state, it does a <b>PostQuitMessage<\/b> to itself.<\/p>\n<hr>\n<h3><a name=\"PostMessage(WM_CLOSE)\">PostMessage(WM_CLOSE)<\/a><\/h3>\n<p>The <i>only<\/i> time an application should shut down is when the user or the<br \/>\nsystem asks it to shut down. This means that the user has used one of the<br \/>\nnumerous means to ask a shutdown of the app (the close box, Alt+F4, the system<br \/>\nmenu, the Task Manager), or the user is logging off or the system is shutting<br \/>\ndown. Otherwise, this has all the charm of using <b><a href=\"#ExitProcess\">ExitProcess()<\/a><\/b><a href=\"#ExitProcess\"><br \/>\nor <b>exit()<\/b><\/a> and is an error. If the program is seriously broken, you<br \/>\nshould <i>still<\/i> keep it running&#8230;just don&#8217;t let it do anything.<\/p>\n<p>Sometimes, shutdown is a multiphase operation. The <b>OnClose<\/b> handler<br \/>\nonly initiates the close operation, but does not actually call the superclass <b>OnClose<\/b><br \/>\nhandler which eventually gets to the built-in <b>DefWindowProc<\/b> which calls <b>DestroyWindow<\/b>.<br \/>\nThis is deferred until the necessary conditions are met, such as network<br \/>\nconnections quiesce, the robotic arm has been retracted to its safe position,<br \/>\nand similar long-period delay operations. In this case, the superclass <b>OnClose<\/b><br \/>\nhandler will be called when the necessary conditions are met.<\/p>\n<hr>\n<h3><a name=\"Using Events for Mutual Exclusion\">Using Events for Mutual<br \/>\nExclusion<\/a><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">potentially fatal<\/a><\/p>\n<p>Events (those objects created by <b>::CreateEvent<\/b> or by using <b>CEvent<\/b>)<br \/>\ncan be used for synchronization, but they are inadequate for doing mutual<br \/>\nexclusion. The reason is that many threads can pass an Event. For mutual<br \/>\nexclusion use a Mutex (created by <b>::CreateMutex<\/b>) or <b>CMutex<\/b> or a <b>CRITICAL_SECTION<\/b>.<br \/>\nIf you are using an Event for mutual exclusion, you are using the incorrect<br \/>\nmechanism and need to change.&nbsp;<\/p>\n<hr>\n<h3><a name=\"Entering a Critical Section before a Lengthy Operation\">Entering a<br \/>\nCritical Section before a Lengthy Operation<\/a><\/h3>\n<p>Severity: <a href=\"#Serious\">serious<\/a>, <a href=\"#Potentially fatal\">potentially fatal<\/a><\/p>\n<p>A Critical Section of any sort (a section of code which is protected from<br \/>\nconcurrent execution on the same data item) should be as short as possible.<br \/>\nGenerally there are a very small number of lines of code between the locking and<br \/>\nthe unlocking, and furthermore these lines do not usually contain lengthy loops.<br \/>\nThe longer you spend in a critical section, the higher the probability that<br \/>\nanother thread will block on the same lock. This decreases total throughput of<br \/>\nyour program.<\/p>\n<p>But one thing that is <i>always<\/i> a mistake is to block before a blocking<br \/>\noperation. I have actually seen code that locks a buffer in the following<br \/>\nfashion (this was in the worker thread).&nbsp;<\/p>\n<pre>\/\/ in the shared data area:\r\nvolatile DWORD length;\r\n----------------------------\r\nlength = 0;\r\nwhile(reading)\r\n   { \/* read loop *\/\r\n    EnterCriticalSection(&amp;bufferlock);\r\n    ReadFile(comport, &amp;buffer[length], bufferlength - length, &amp;bytesRead, NULL);\r\n    length += bytesRead;\r\n    LeaveCriticalSection(&amp;bufferlock);\r\n    mainthread-&gt;PostMessage(UWM_DATA_READ);\r\n   } \/* read loop *\/<\/pre>\n<p>The main GUI loop was then supposed to read the data by doing<\/p>\n<pre>LRESULT CView::OnDataRead(WPARAM, LPARAM)\r\n   {\r\n    EnterCriticalSection(&amp;bufferlock);\r\n    ... use data in buffer...\r\n    length = 0; \/\/ reset the length\r\n    LeaveCriticalSection(&amp;bufferlock);\r\n   }<\/pre>\n<p>There are two deep and unrecoverable bugs in this code. The programmer had<br \/>\nanalyzed it as &quot;I can only have one thread at a time accessing the buffer<br \/>\nand the length, so I have done proper synchronization&quot;. However, the<br \/>\ncrucial problem was that there was never really a time when the buffer was <i>unlocked<\/i>.<br \/>\nBy the time the <b>PostMessage<\/b> was processed, the buffer was locked again!<br \/>\nConsider the execution of the loop: it leaves the critical section, posts the<br \/>\nmessage, loops around, locks the critical section again, and blocks on the <b>ReadFile<\/b>.<br \/>\nSo by the time the message is processed in the main GUI thread, the thread is<br \/>\nblocked when it tries to enter the critical section. When the worker thread<br \/>\nunblocks, it fills in the buffer, releases the lock, posts a message, loops<br \/>\naround, and locks the critical section. Boom!<\/p>\n<p>Now the second fatal bug is the fact that there is <i>no test for buffer<br \/>\noverrun<\/i>. That is, if you look at this, it just keeps reading data from the<br \/>\nserial port. Because the main thread can never get a chance to reset the <b>position<br \/>\n<\/b>to zero, it merely keeps increasing. When the <b>position<\/b> gets to be<br \/>\ngreater than <b>bufferlength<\/b>, the computation <b>bufferlength&nbsp;&#8211;&nbsp;position<\/b><br \/>\ngives a negative number, but since the input is a <b>DWORD<\/b>, this turns out<br \/>\nto be a massively large positive number. Since the buffer is <i>not<\/i> as long<br \/>\nas the large negative number suggests, the inevitable result is that the I\/O<br \/>\nManager will reject the <b>ReadFile<\/b> by throwing an access fault<br \/>\nexception.&nbsp;<\/p>\n<p>The trick here is to never, ever lock the buffer during the I\/O operation.<br \/>\nThe best method would be to have the thread allocate an input buffer on the<br \/>\nstack, and upon completion, allocate a block of storage to hold the data and <b>PostMessage<\/b><br \/>\na pointer to the heap block to the main GUI thread which handles it. This is<br \/>\nsimilar to the technique that I describe in my essay on worker threads, except I<br \/>\nwouldn&#8217;t use <b>CString&nbsp;*<\/b> for the data because the data could contain<br \/>\nembedded NUL bytes, which would be incompatible with <b>CString<\/b>. I might <b>PostMessage<\/b><br \/>\na simple <b>BYTE&nbsp;*<\/b> pointer in <b>WPARAM<\/b> and the length in <b>LPARAM<\/b>,<br \/>\nor I might use a <b>CArray&lt;BYTE, BYTE&gt;&nbsp;*<\/b>, or, if I were a user of<br \/>\nSTL, some STL array structure. At no time would any locking be required.<\/p>\n<p>Alternatively, it is worth observing that if I put a lock simply around the<br \/>\nsetting and examination of the buffer length, there would only be a very small<br \/>\nwindow of locking, and furthermore the locking would essentially be guaranteed<br \/>\nto complete in a nominally brief period of time (excluding effects of thread<br \/>\npriorities). However, I would be disinclined to use this method when a simpler<br \/>\nmethod already exists. Note that the performance issue doesn&#8217;t arise because the<br \/>\nentire allocation and message handling task completes in less than a single<br \/>\ncharacter time at any serial port speed, and would therefore be undetectable.<br \/>\nAgain, refer to my essay on &quot;<a href=\"optimization.htm\">Optimization, Your<br \/>\nWorst Enemy<\/a>&quot;. Why introduce complexity when it is not needed?<\/p>\n<hr>\n<h3><a name=\"Using SetCurrentDirectory\">Using SetCurrentDirectory<\/a>\/_chdir<\/h3>\n<p>Severity: <a href=\"#Poor style\">poor style<\/a>\/<a href=\"#Potentially fatal\">potentially<br \/>\nfatal<\/a><\/p>\n<p>There are some very rare occasions in which it makes sense to change the<br \/>\nworking directory. Every one of them is at the explicit request of the user. It<br \/>\nis <i>never<\/i> appropriate to simply change it. Possibly the worst example of<br \/>\nthe misuse of <b>SetCurrentDirectory<\/b> (or its C-library equivalent, <b>_chdir<\/b>)<br \/>\nis in programs that try to do recursive tree walks during wildcard searches. The<br \/>\nproblem with this call is that it changes the working directory for the entire<br \/>\nprocess, meaning that every thread sees the effect of this. Since many threads<br \/>\nopen or create files based on the current directory setting, a thread that<br \/>\ncreates a file while another thread is changing the directory will end up<br \/>\ncreating it in some random place.&nbsp;<\/p>\n<p>The changing of a directory should only be a consequence of the user<br \/>\nrequesting a change to a specific directory. Changing it at any other time, for<br \/>\nany other reason, that does not involve the user explicitly specifying the<br \/>\ndirectory (often as part as executing one of the file dialogs or a <b>ShBrowseForFolder<\/b><br \/>\ndialog), can be thought of as a serious error. The programmer does not have the<br \/>\nright to spontaneously change the current directory. To do so is at the very<br \/>\nleast exceedingly poor style, and at worst it can have potentially fatal<br \/>\nconsequences if you have multiple threads.&nbsp;<\/p>\n<hr>\n<h3><a name=\"Polling process\">Polling for process completion<\/a><\/h3>\n<p>Severity: <a href=\"#Inefficient\">inefficient<\/a><\/p>\n<p>A common failure mode in multithreaded programming is to have some thread<br \/>\n&quot;wait&quot; for another by asking &quot;are we there yet? are we there<br \/>\nyet?&quot;. All this accomplishes is to waste a significant amount of CPU time,<br \/>\nsince, unless you have a multiprocessor, the thread that is &quot;waiting&quot;<\/p>\n<p>will consume its entire time slice asking for a condition <i>that cannot<br \/>\npossibly be set to true<\/i> because during the time that thread is running, the<br \/>\nthread that is being waited for <i>is not running<b> <\/b><\/i>and therefore<br \/>\ncannot possibly change the state! Putting this thread in a separate process is<br \/>\nno different from polling for thread completion in the same process. <b>GetExitCodeProcess<\/b><br \/>\nis as pointless as <b><a href=\"#Polling\">GetExitCodeThread<\/a><\/b>. If you want<br \/>\nto <i>see<\/i> the process exit code, you do this <i>after<\/i> you have<br \/>\ndetermined the process has finished. Since most processes don&#8217;t return a<br \/>\nmeaningful code, even that is usually pointless.<\/p>\n<p>In a multiprocessor, it means the waiting processor simply wastes a<br \/>\nsignificant amount of its time waiting for a thread to finish; that time could<br \/>\nbe better spent doing something productive, such as running one of the other<br \/>\nthreads of your application, or some other application, or a thread of the<br \/>\napplication you are waiting for.<\/p>\n<p>There are three techniques for dealing with process completion. The simplest<br \/>\nmethod, which I will explain why has serious defects in a <a href=\"#Blocking the main GUI thread\">different<br \/>\nsection<\/a> of this essay, is to simply do a <b>WaitFor&#8230;<\/b> operation on the<br \/>\nprocess handle. The process handle remains non-signaled as long as the process<br \/>\nis running (or potentially runnable) and becomes signaled when the process<br \/>\nterminates. Therefore, the thread that is waiting for the completion uses no CPU<br \/>\ntime while it is waiting. However, since this blocks the waiting thread, and<br \/>\nthat can be the main GUI thread, this is not generally recommended in the main<br \/>\nthread.<\/p>\n<p>The second method is useful when you have a console-style app for which you<br \/>\nhave redirected <b>stdout<\/b>, which you are receiving via an unnamed pipe in<br \/>\nyour application. When the pipe is broken, it typically means that the<br \/>\napplication has finished, since very few applications would spontaneously close <b>stdout<\/b>.<br \/>\nIt is usually closed implicitly when the process finishes.<\/p>\n<p>The third method is to create a thread that waits for the process to<br \/>\ncomplete, and posts a user-defined message to the appropriate window (view or<br \/>\nmainframe) to indicate that the process has finished. This is discussed in the<br \/>\nnext section and in an <a href=\"processes.htm\">accompanying essay<\/a>.<\/p>\n<hr>\n<h3><a name=\"TryEnterCriticalSection\">TryEnterCriticalSection<\/a><\/h3>\n<p>Severity: <a href=\"#Inefficient\">inefficient<\/a><\/p>\n<p>I find this a pointless operation. The whole idea of a critical section is<br \/>\nthat you should block if you can&#8217;t enter it. But here is a call that simply<br \/>\nreturns <b>FALSE<\/b> if you can&#8217;t enter the critical section. What can you do?<br \/>\nWell, retry the operation. This is very much like polling. If you need a<br \/>\ntimeout, use a <b>Mutex<\/b> and a <b>WaitForSingleObject<\/b> with a timeout. So<br \/>\nI find that this does not seem to solve any problem that matters, but the few<br \/>\ntimes I&#8217;ve seen it used it results in a merely inefficient program, and in one<br \/>\ncase an erroneous program.<\/p>\n<p>And, I should point out, that the following are <i>not<\/i> equivalent:<\/p>\n<pre>::WaitForSingleObject(mutex, timeout);<\/pre>\n<pre>while(!TryEnterCriticalSection(&amp;lock)) \r\n       Sleep(deltaT);<\/pre>\n<p>In the first form, the wait blocks the thread until either the <b>mutex<\/b><br \/>\nhandle becomes signaled or the timeout occurs, whichever occurs first. In the<br \/>\nsecond form, if the <b>TryEnterCriticalSection<\/b> fails, the thread <i>always<\/i> <\/p>\n<p>blocks for the <b>deltaT<\/b> time. If the lock becomes signaled 0.1ms after the<br \/>\n<b>TryEnterCriticalSection<\/b>, the loop still waits the full <b>deltaT<\/b><br \/>\nbefore testing again. Think about it This is like calling up tech support,<br \/>\nfinding there is someone ahead of you in the queue, and waiting five minutes<br \/>\nbefore calling back. There is an excellent chance you will never, ever get<br \/>\nsupport.<\/p>\n<hr>\n<h3><a name=\"Block on Process\">Blocking the main GUI thread waiting for process<br \/>\ncompletion<\/a><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">potentially fatal<\/a><\/p>\n<p>This is almost always an error. For one thing, if you are capturing output<br \/>\nfrom the process, you won&#8217;t be able to display it, because even if the I\/O is<br \/>\ndone in a separate thread, the updating of the main GUI controls is handled by<br \/>\nthe GUI threads. So the net result is that the program appears to not work at<br \/>\nall. Never block the main GUI thread if you can help it. Certainly never block<br \/>\nit waiting for process completion.<\/p>\n<p>Note that this is more serious than just blocking a thread and getting a<br \/>\nnon-responsive GUI, which is merely annoying to the user. Your whole program can<br \/>\nsimply hang. So it goes beyond poor interface strategy and falls into the<br \/>\npotentially fatal class.<\/p>\n<p>As with asynchronous thread notification, you simply disable all controls,<br \/>\nmenu items, etc. that are inappropriate while the process is running. You&#8217;ve<br \/>\nseen this happen when you run a Build under the VC++ IDE. If you drop down the <b>Build<\/b><br \/>\nmenu, there are lots of menu items enabled, but <b>Stop Build<\/b> is disabled.<br \/>\nIf you select a build option and the compiler is running, all the other options<br \/>\nare disabled but <b>Stop Build<\/b> is enabled. This is simple <b>OnUpdateCommandUI<\/b><br \/>\nhandling.<\/p>\n<p>What I do is have a Boolean that enables\/disables the controls. It is set to <b>TRUE<\/b><\/p>\n<p>when a process is running and <b>FALSE<\/b> when a process completes.<\/p>\n<pre>class waitInfo {\r\n   public:\r\n      waitInfo(HANDLE p, CWnd * wnd) {process = p; recipient = wnd; }\r\n      HANDLE process;\r\n      CWnd * recipient;\r\n};\r\n\r\n...AfxBeginThread(waiter, new waitInfo(procinfo.hProcess, this));\r\nprocessRunning = TRUE;\r\n\r\n\r\n\/* static *\/ UINT CMyView::waiter(LPVOID p)\r\n    {\r\n     waitInfo * info = (waitInfo *)p;\r\n     ::WaitForSingleObject(info-&gt;process, INFINITE);\r\n    recipeint-&gt;PostMessage(UWM_PROCESS_FINISHED, (WPARAM)info-&gt;process);\r\n    delete info;\r\n    return 0;\r\n   }\r\n\r\nLRESULT CMyView::OnProcessFinished(WPARAM, LPARAM)\r\n   {\r\n    processRunning = FALSE;\r\n    return 0;\r\n   }\r\n\r\nvoid CMyView::OnRunProcess(CCmdUI * pCmdUI)\r\n   {\r\n    pCmdUI-&gt;Enable(!processRunning);\r\n   }<\/pre>\n<hr>\n<h3><a name=\"setjmp C++\">Using setjmp\/longjmp in a C++ program<\/a><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">fatal<\/a>. No &quot;potentially&quot; about it.<\/p>\n<p>These are functions that are such an outrageous kludge that I&#8217;m not going to<br \/>\ndignify them with an explanation of how they work internally. They don&#8217;t work, never did.<br \/>\nThe only reason they gave the appearance of working was the incredibly poor<br \/>\nquality of the PDP-11 C compiler, which ran in 64K of memory and generated lousy<br \/>\ncode. The technique couldn&#8217;t possibly work in any modern optimizing compiler,<br \/>\nand didn&#8217;t. Been there, done that.&nbsp;<\/p>\n<p>The essence of <b>setjmp<\/b> was that it marked a place to which control<br \/>\nwould transfer when a <b>longjmp<\/b> was executed. It would return with 0 when<br \/>\ncalled directly and nonzero (the <b>longjmp<\/b> value) if it was an abnormal<br \/>\nreturn.<\/p>\n<p>Today, this is handled with exceptions. <b>setjmp<\/b> is replaced by <b>TRY\/CATCH<\/b><\/p>\n<p>and <b>longjmp<\/b> is replaced by <b>throw<\/b>. Key here is that in C++, these<br \/>\nare first-class concepts in the language and not subject to the horrendous bugs<br \/>\nthat <b>setjmp\/longjmp<\/b> generated in most compilers (the compiler was working<br \/>\ncorrectly; the <b>longjmp<\/b> logic would produce erroneous results). But the <i>major<b><br \/>\n<\/b><\/i>failure mode of <b>longjmp<\/b> is that it bypasses all destructors on<br \/>\nthe stack, with inevitably fatal consequences<b>.<\/b><\/p>\n<p>Bottom line: if you have <b>setjmp\/longjmp<\/b> in a C++ program, you have a<br \/>\nfatally flawed program. Remove them and replace them with C++ exception<br \/>\nhandling.<\/p>\n<p>Note: If you believe there is any justification for <b>setjmp\/longjmp<\/b> in<br \/>\na C++ program, you are wrong. Don&#8217;t try to justify the situation, <i>fix it<\/i>.<br \/>\n(Seriously, I&#8217;ve had people argue this point with me. It takes less time to fix<br \/>\nthe problem than to try to justify why it makes sense).<\/p>\n<hr>\n<h3><a name=\"setjmp GUI\">Using setjmp\/longjmp in any GUI program<\/a><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">potentially fatal<\/a> (except if the<br \/>\nGUI program is written in C++, in which case <a href=\"#setjmp C++\">it is <i><\/p>\n<p>always<\/i> a fatal error<\/a>)<\/p>\n<p>Yes, I&#8217;ve done it. In Win16. With optimizations turned off, because the<br \/>\nbrain-dead third-party library we were using demanded that we support it. I<br \/>\nwould never support it willingly. There is no excuse for using it in Win32. The<br \/>\nproblem in a GUI program is that you can end up with state that is not cleaned<br \/>\nup, operations that do not complete, and a plethora of other problems. And I<br \/>\ncover these in the next section.<\/p>\n<hr>\n<h3><a name=\"setjmp\">Using setjmp\/longjmp in any program<\/a><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">potentially fatal<\/a> (except if the<br \/>\nprogram is written in C++, in which case <a href=\"#setjmp C++\">it is <i>always<\/i> <\/p>\n<p>a fatal error<\/a>)<\/p>\n<p>If you are programming in C, use Structured Exception Handling. If you want<br \/>\nportability, you cannot tolerate setjmp\/longjmp in any case because it is only<br \/>\nbarely functional. To make it work correctly, you must declare every local<br \/>\nvariable as <b>volatile<\/b>, and that&#8217;s just the start. You must not use the <b>register<\/b><br \/>\nqualification on any local variable or parameter. There are limits how <b>setjmp<\/b><br \/>\ncan be called. There are nonportable limitations on the contexts in which <b>longjmp<\/b><br \/>\ncan be called. Managing the <b>longjmp<\/b> buffer is a real royal pain. They<br \/>\ndon&#8217;t nest without a lot of effort. Given we now have linguistic mechanisms that<br \/>\nget rid of the need for this horror, it is best to avoid it.<\/p>\n<p>Essentially, if I see this in a program, I know the program is working only<br \/>\nby amazing good fortune.<\/p>\n<hr>\n<h3><a name=\"clipboard\">Using the clipboard for anything other than copy or cut<\/a><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\"> fatal<\/a>. This is so incredibly<br \/>\nbogus that it is impossible to classify it as anything else.<\/p>\n<p>No, it isn&#8217;t fatal to your program. Programs that violate this rule will<br \/>\nprobably continue to work just fine. Just don&#8217;t <i>ever<\/i> be caught in a dark<br \/>\nalley with one of your users!<\/p>\n<p>You, the programmer, <i>do not have the right to modify the clipboard<br \/>\ncontents<\/i>. Only the <i>user<\/i> has the right to modify those contents. Thus,<br \/>\nthe <i>only<\/i> time you are permitted to modify the contents of the clipboard<br \/>\nis when the user has <i>requested you to<\/i> by doing a copy-related or<br \/>\ncut-related action. You may not modify it at any other time. I&#8217;ve seen people<br \/>\nuse it for interprocess communication. This is <i>absolutely beyond any shadow<br \/>\nof a doubt the <b><font color=\"#FF0000\">WRONG<\/font><\/b> thing to do<\/i>. There<br \/>\nis no way to emphasize this strongly enough. Only if the <i>user<\/i> has an<br \/>\nexplicit operation that says &quot;Put this in the clipboard&quot; are you<br \/>\npermitted to change the clipboard contents. It could be a menu item, a popup<br \/>\nmenu item, <b>Ctrl+C<\/b>, <b>Ctrl+X<\/b>, a pushbutton that says<\/p>\n<p>&quot;copy&quot;, or anything else. Then, and <i>only<\/i> then, are you<br \/>\npermitted to change the clipboard contents.<\/p>\n<p>Imagine the following: your program is running. It fires off another program<br \/>\nto run. It puts something in the clipboard to send to that program. However, I<br \/>\nleft out something in this sequence. The <i>real<\/i> sequence is<\/p>\n<ul>\n<li>Your program starts<\/li>\n<li>While your program is running, the user opens some other document,<br \/>\n    probably from another application<\/li>\n<li>The user does a Cut operation<\/li>\n<li>The user closes the document, saving the contents which have had something<br \/>\n    removed<\/li>\n<li>Your program drops trash into the clipboard<\/li>\n<li>The user brings up another app and does a Paste operation, expecting to<br \/>\n    get the valuable information which has been cut to the clipboard<\/li>\n<li>The user puts out a contract on you<\/li>\n<\/ul>\n<hr>\n<h3><a name=\"Sleep\">Sleep(<i>n<\/i>)<\/a><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">potentially fatal<\/a><\/p>\n<p>There are valid reasons for using <b>Sleep<\/b>. However, the most common<br \/>\nusages I find of them are completely wrong-headed and in most cases result in<br \/>\nfatal flaws in the programs.<\/p>\n<p>First, you have to understand what the value of <i>n<\/i> means: it means,<br \/>\n&quot;Stop this thread for at least <i>n<\/i> milliseconds&quot;. The thread will<br \/>\nresume sometime after that. Perhaps a long time after that. So if you say<\/p>\n<p>&quot;Sleep(5)&quot; the likelihood that your thread will be running 5ms later<br \/>\nis nearly zero. This is because the basic clock is 10 or 15 ms (or in MS-DOS, 55 ms,<br \/>\nbut I consider those systems dead), so it cannot possibly run sooner than one<br \/>\nclock tick. But if a higher priority thread is running, it will <i>not<\/i> be<br \/>\npreempted, so it might be several timeslices before the thread which is now<br \/>\nrunnable can actually run. Even if you think you have control of the priorities,<br \/>\nyou don&#8217;t, because the Balance Set Manager thread may be running, and it can<br \/>\nboost any thread to priority 15 and give it a double timeslice, and in NT, there<br \/>\nare file system and other kernel threads, and Deferred Procedure Calls (DPCs)<br \/>\nthat will also preempt. Read my essay &quot;<a href=\"time.htm\">Time is the<br \/>\nsimplest thing<\/a>&quot; for more details.<\/p>\n<p>Mostly, when I spot a <b>Sleep()<\/b> call in a program, I ask &quot;Why is<br \/>\nthis here?&quot; and the answer is &quot;Because the threads won&#8217;t work unless<br \/>\nit is&quot;. What this means is the multithreading architecture is irrevocably<br \/>\nflawed and needs to be rethought and perhaps rewritten. Throwing a <b>Sleep()<\/b><\/p>\n<p>call may give the illusion that you have solved the problem, but in fact there<br \/>\nis a fundamental problem, and the <b>Sleep()<\/b> call disguises it. However, on<br \/>\na faster machine, or a different version of the operating system, or a different<br \/>\nmix of applications, or a different loading factor on your app, or most<br \/>\nespecially, on a multiprocessor, you <i>will <\/i>discover<br \/>\nthat the fundamental architecture is flawed. At that point, you don&#8217;t have a<br \/>\nchoice.<\/p>\n<p>True story: some time ago I was consulting with a client, doing a code<br \/>\nwalkthrough of their multithreaded application. I spotted a <b>Sleep()<\/b> and<br \/>\nknew immediately that this was where the problem was. I didn&#8217;t know <i>what<\/i><br \/>\nthe problem was, but I knew I had found it. After some explanation by their<br \/>\nprogrammer (which<br \/>\nincluded &quot;the threading doesn&#8217;t work right if it isn&#8217;t there&quot;) I<br \/>\nunderstood the code, and said &quot;This will fail under the following<br \/>\nconditions&quot; and proceeded to outline the conditions, and said &quot;and it<br \/>\nwill fail in the following ways&quot; and listed a set of ways the program would<br \/>\nfail. They were impressed. I had described <i>exactly<\/i> the conditions under<br \/>\nwhich it failed and the manner of the failures, without ever having seen the<br \/>\nprogram run. It had taken me perhaps 15 seconds to spot the <b>Sleep()<\/b> call<br \/>\n(they had said &quot;Here&#8217;s the function that is failing&quot; so I didn&#8217;t have<br \/>\nto look for it). How did I do this so quickly? Because it was by no means the<br \/>\nfirst such instance I had seen! And in every previous time I had been absolutely<br \/>\ncorrect.<\/p>\n<p>Another case I see all too often is after a <b>::CreateProcess<\/b> call there<br \/>\nis a <b>Sleep()<\/b> call, &quot;to give the process time to come up&quot;. No matter what<br \/>\nvalue is chosen here, it is wrong. There <i>is no correct value for this <b><br \/>\nSleep()<\/b> call!<\/i> Either it is too short, or too long, but it will <i>never<\/i> <\/p>\n<p>be &quot;just right&quot;. There is a simpler method if you are waiting for a GUI app to<br \/>\nbecome active, with its window fully displayed. Use the <b>WaitForInputIdle<\/b><br \/>\nAPI call. You can put a timeout on it, but this timeout is usually fairly large<br \/>\nand is intended to indicate that you are in really deep yogurt, somewhere down<br \/>\nin the boysenberries. If the timeout is selected properly, it will be fairly<br \/>\nlong, and it means that the process has failed to come up at all.<\/p>\n<p>There are occasional cases in which a <b>Sleep()<\/b> makes sense. But they<br \/>\nare so rare, and so special-case, that I can&#8217;t give a general rule by which you<br \/>\ncan determine that it is a valid usage. But keep in mind that most uses are <i>not<\/i><br \/>\nvalid or sensible. And also it means that any constant you choose for the timing<br \/>\nvalue is probably wrong, also. In my multithreading lab, I demonstrate a case of<br \/>\nusing <b>Sleep(5000)<\/b> to make the program work. I then force the students to<br \/>\nconsider all the ways <i>this<\/i> can fail, and why any value, 5000, 10000,<br \/>\n1000, etc. will <i>always <\/i>be wrong. Then I force them to rethink how the<br \/>\nsynchronization between the threads is done. When we are finished, we have a <i>correct<\/i>,<\/p>\n<p><b>Sleep<\/b>-free program.<\/p>\n<p>There are times when <b>Sleep(0)<\/b> is handy to produce interesting<br \/>\nanimation effects in multithreaded programs; <b>Sleep(0)<\/b> forces the current<br \/>\nthread to yield and allows another thread to run. This is in general<br \/>\ninefficient, because it induces a lot of gratuitous context swaps and scheduling<br \/>\noperations, but for some animation effects to illustrate the effects of<br \/>\nmultithreading it really makes a nice visual effect. But you have to be willing<br \/>\nto give up a fair amount of CPU resource to use this, and it is very special<br \/>\ncase.<\/p>\n<hr>\n<h3><a name=\"SleepEx\">Using SleepEx()<\/a><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">potentially fatal<\/a>, <i>or<\/i><\/p>\n<p>absolutely essential<\/p>\n<p><b>SleepEx()<\/b> has all of the charm of <b>Sleep()<\/b>. It differs only<br \/>\nslightly in that it takes two<br \/>\nparameters; one of which is the sleep interval and one of which is a Boolean<br \/>\nindicating if pending Asynchronous Procedure Calls (APCs) should be taken. The<br \/>\ncombination <b>SleepEx(0, TRUE)<\/b> has the characteristic that it does not<br \/>\nreally suspend the thread, but allows any pending APCs to be taken. If there are<br \/>\nany APCs, they will be processed before the <b>SleepEx<\/b> continues. Thus, if<br \/>\nyou are using asynchronous I\/O, this is actually not only a useful call, but in<br \/>\nsome ways an <i>essential<\/i> call (You could also use <b>WaitFor&#8230;Ex()<\/b><\/p>\n<p>calls). So you can feel free to use it in the context of pending asynchronous<br \/>\ncallback I\/O. If you are not using one of the <b>WaitFor&#8230;Ex()<\/b> calls you <i>must<\/i><br \/>\nuse <b>SleepEx(<i>n<\/i>, TRUE)<\/b>.<\/p>\n<hr>\n<h3><a name=\"Polling for time\">Polling for time<\/a><\/h3>\n<p>Severity: <a href=\"#Inefficient\">inefficient<\/a> to <a href=\"#Potentially fatal\">potentially<br \/>\nfatal<\/a><\/p>\n<p>This is one of the most common errors I&#8217;ve seen. The idea is to somehow ask<br \/>\nthe system about how much time has elapsed and then take some action based on a<br \/>\nchange in time. Most of the code I&#8217;ve seen to do this is usually bizarre or<br \/>\nconvoluted. And mostly seems to be based on some illusions about what time is.<br \/>\nAs a prerequisite to doing anything with time, you should read my essay on <a href=\"time.htm\">time<\/a>.<\/p>\n<p>First, you can&#8217;t poll for time. This just wastes CPU time with no guarantees<br \/>\nthat anything meaningful will happen.<\/p>\n<p>As pointed out in my essay, the <i>resolution<\/i> of a time value has nothing<br \/>\nto do with the <i>precision<\/i> that is used to represent it. For example, a<br \/>\ntime value that can be stored in milliseconds. I&#8217;ve seen code that goes like<br \/>\nthis<\/p>\n<pre>SYSTEMTIME t0;\r\nGetSystemTime(&amp;t0);<img loading=\"lazy\" decoding=\"async\" border=\"0\" src=\"no.gif\" align=\"right\" width=\"65\" height=\"62\">\r\n\r\nwhile(TRUE)\r\n   { \/* pause loop *\/\r\n    SYSTEMTIME now;\r\n    GetSystemTime(&amp;now);\r\n    if(abs(t0.wMilliseconds - now.wMilliseconds) &gt; 1)\r\n      { \/* 1 ms passed *\/\r\n       break;\r\n      } \/* 1 ms passed *\/\r\n   } \/* pause loop *\/<\/pre>\n<p>Actually, this code was written because the programmer said &quot;But you<br \/>\nsaid that the resolution of the <b>Sleep()<\/b> function was only 10ms, so this<br \/>\ngets around that!&quot;. Actually, the system time increments by some number of<br \/>\nmilliseconds on each clock tick, and consequently if you write a program that<br \/>\nsimply reads the time in a tight loop, the minimum difference you will see is<br \/>\n10ms or 15ms. So this code is identical to <b>Sleep(1)<\/b> without the<br \/>\nsimplicity, and will resume sometime between 1ms and 10ms after the call. So the<br \/>\nabove code is fatally flawed. Not only is it inefficient, it doesn&#8217;t do what it<br \/>\nclaims to do.<\/p>\n<p>An even worse case was one where the programmer wanted to activate something<br \/>\nat 8 a.m.. The code was similar to this:<\/p>\n<pre>void DoAtEight()\r\n   {\r\n    while(TRUE)\r\n      { \/* Wait loop *\/\r\n       CTime t = CTime::GetCurrentTime();\r\n       CString s = t.Format(_T(&quot;%H:%M:%S&quot;));\r\n       if(s == _T(&quot;08:00:00&quot;))\r\n         { \/* 8am *\/\r\n          ...do processing...;\r\n         } \/* 8am *\/\r\n      } \/* Wait loop *\/\r\n   }<\/pre>\n<p>Now this code cannot possibly work reliably. First, the programmer observed<br \/>\nthat the machine ran somewhat sluggishly and Task Manager showed that the<br \/>\napplication was consuming 100% of the CPU time. This should not be surprising;<br \/>\nthe code sits there and keeps asking &quot;are we there yet?&quot; &quot;are we<br \/>\nthere yet?&quot; and will only be suspended when it has exhausted its timeslice.<br \/>\nBut what is worse, this code cannot work. Consider: a timeslice is about 200ms<br \/>\n(the details vary based on the fundamental time tick). So suppose that at<br \/>\n07:59:59.99, the last time read, the thread executing this code is suspended.<br \/>\nThere are ten other threads waiting their turn. The next time the waiting thread<br \/>\nis scheduled, it reads the time, and finds that the time is now 08:00:01.13. So<br \/>\nat no time will the string representing the time ever be 08:00:00. Now on some<br \/>\ndays this will work, but on other days it will fail. In addition, in the<br \/>\nunlikely chance that the time read was actually 08:00:00, if the processing<br \/>\ntakes less than one second, there is an excellent chance that the next time<br \/>\nthrough the loop the&nbsp; time might <i>again<\/i> be 08:00:00, causing the<br \/>\nprocessing code to be executed two or more times, instead of the once that was<br \/>\ndesired. All in all, possibly the worst possible way to accomplish the task.<\/p>\n<p>My proposed solution was to do something like this:<\/p>\n<pre>void DoAtEight()\r\n    {\r\n     BOOL processed = FALSE;\r\n     while(TRUE)\r\n       { \/* wait loop *\/\r\n        CTime t = CTime::GetCurrentTime();\r\n        if(t.GetHour() &gt;= 8 &amp;&amp; !processed)\r\n          { \/* process it *\/\r\n           processed = TRUE;\r\n           ...do processing...;\r\n          } \/* process it *\/\r\n        else\r\n        if(t.GetHour() &lt; 8)\r\n           processed = FALSE;\r\n        Sleep(60000); \/\/ wait for a minute, or a bit more\r\n       } \/* wait loop *\/\r\n     }<\/pre>\n<p>This is still not optimal; it wakes up once a minute, performs its test, and<br \/>\ngoes back to sleep. It would be even better to use a waitable timer.<\/p>\n<pre>void DoAtEight()\r\n   {\r\n    HANDLE timer = ::CreateWaitableTimer(NULL, FALSE, NULL);\r\n    BOOL processed = FALSE;\r\n    while(TRUE)\r\n      { \/* wait loop *\/\r\n       SYSTEMTIME t0;\r\n       ::GetSystemTime(&amp;t0);\r\n       if(t0.wHour &gt; 8)\r\n         { \/* adjust to tomorrow *\/\r\n          ULARGE_INTEGER t;\r\n          ::SystemTimeToFileTime(&amp;t0, (FILETIME *)&amp;t);\r\n          t += 24ui64 * \/\/ hours in a day\r\n               60ui64 * \/\/ minutes in an hour\r\n               60ui64 * \/\/ seconds in a minute\r\n             1000ui64 * \/\/ milliseconds in a second\r\n             1000ui64 * \/\/ microseconds in a millisecond\r\n               10ui64;  \/\/ 100 ns units in a microsecond\r\n          ::FileTimeToSystemTime((FILETIME *)&amp;t, &amp;t0);\r\n         } \/* adjust to tomorrow *\/\r\n       t0.wHour = 8;\r\n       t0.wMinute = 0;\r\n       t0.wSecond = 0;\r\n       t0.wMilliseconds = 0;\r\n       LARGE_INTEGER alarm;\r\n       ::SystemTimeToFileTime(&amp;t0, (FILETIME *)&amp;alarm);\r\n       ::SetWaitableTimer(timer, &amp;alarm, 0, NULL, NULL, FALSE);\r\n       ::WaitForSingleObject(timer, INFINITE);\r\n       ...do processing...\r\n      } \/* wait loop *\/\r\n   }<\/pre>\n<hr>\n<h3><a name=\"malloc\">Use of malloc\/free in C++ programs<\/a><\/h3>\n<p>Severity: <a href=\"#Poor style\">poor style<\/a>,<br \/>\n<a href=\"#Potentially Harmful\">potentially harmful<\/a><\/p>\n<p>There is no reason I can imagine to use <b>malloc<\/b> or <b>free<\/b> in a C++<br \/>\nprogram. If you need them, there are useful alternatives. For example, if you<br \/>\nneed a dynamically-allocated buffers of <i>n<\/i> bytes, the simplest way is <i>not<\/i><\/p>\n<p>to write<\/p>\n<pre>    BYTE * buffer = malloc(n);<\/pre>\n<p>but to write<\/p>\n<pre>    BYTE * buffer = new BYTE[n]; <\/pre>\n<p>They perform the same action, so why use an obsolete allocation mechanism.<\/p>\n<p>Why does this matter? Consider the following: I need an array of objects, so<br \/>\nI allocate them as follows:<\/p>\n<pre>typedef struct {\r\n     int x;\r\n     int y;\r\n} Coordinate;<\/pre>\n<pre>Coordinate * coordinates = (Coordinate *)malloc(<i>n<\/i> * sizeof(Coordinate));<\/pre>\n<p>Looks good, right? Works fine, right? Sure. This week. But now I change the<br \/>\nstructure to<\/p>\n<pre>typedef struct {\r\n   int x;\r\n   int y;\r\n   CString description;\r\n} Coordinate;<\/pre>\n<p>Now what happens? The <b>malloc<\/b> operation <i>does not call the <b>CString<\/b><\/i><b><br \/>\n<\/b><i>constructor<\/i>. You have garbage. Your program crashes.&nbsp;<\/p>\n<p>The correct solution was to have always written the code as<\/p>\n<pre>Coordinate * coordinates = new Coordinate[<i>n<\/i>];<\/pre>\n<p>This works, and it will <i>always<\/i> work correctly, even if you later add<br \/>\nmembers to the structure that require constructors. Writing code that breaks<br \/>\nwhen apparently irrelevant changes are made is always a Bad Idea. And since<br \/>\nthere is no possible justification for using <b>malloc<\/b>, why bother writing<br \/>\nincorrect code?<\/p>\n<p>Yes, I&#8217;ve heard the argument, &quot;<b>malloc<\/b> is faster&quot;. I have<br \/>\nsome advice for anyone who advocates this: Get A Life. You are clueless. An<br \/>\nallocation takes thousands of instructions. The trivial overhead introduced by<br \/>\nusing <b>new<i> <\/i><\/b>is unmeasurable. This is a classic example of the<br \/>\n&quot;let&#8217;s optimize at the instruction level&quot; when the real costs are at<br \/>\nthe architecture level. If you are allocating frequently enough that you think<br \/>\nthis trivial overhead can matter, you are very confused; why are you allocating<br \/>\nat all? The real issue is to make programs efficient, and you don&#8217;t accomplish<br \/>\nthat by worrying about unmeasurable overheads when the real costs (such as the<br \/>\nactual cost of the allocator) swamp it by two to four orders of magnitude.<\/p>\n<p>An even worse situation I&#8217;ve seen is the mixing of <b>malloc<\/b> with <b><br \/>\ndelete<\/b>, or even <b>new<\/b> with <b>free<\/b>. There is no possible<br \/>\njustification for such insanity. If it exists, you are wrong. Fatally wrong (no<br \/>\n&quot;potentially&quot; here!). Fix the code. Pretend <b>malloc<\/b> and <b>free<\/b> are<br \/>\nobsolete and should never, ever be used in a C++ program.<\/p>\n<hr>\n<h3><a name=\"GlobalAlloc\">Use of GlobalAlloc\/GlobalLock\/GlobalUnlock\/GlobalFree<\/a><\/h3>\n<p>Severity: <a href=\"#Inefficient\">inefficient<\/a>, <a href=\"#Deeply suspect\">deeply<br \/>\nsuspect<\/a> (except those cases where it is mandated)<\/p>\n<p>These APIs are essentially obsolete, with a very few exceptions. Only when<br \/>\nyou have one of these exceptions should you ever consider these as viable<br \/>\nentities. Otherwise, use <b>new<\/b>\/<b>delete<\/b>. They are relatively<br \/>\ninefficient in terms of both time and space.&nbsp;<\/p>\n<p>The contexts that I am aware of are the clipboard, where you must provide a<br \/>\nglobal memory handle This must be allocated by <b>GlobalAlloc<\/b>. You use <b>GlobalLock<\/b><\/p>\n<p>to make its address available, <b>GlobalUnlock<\/b> when you are done with it,<br \/>\nand you <i>never<\/i> call <b>GlobalFree<\/b> on a clipboard handle, under any<br \/>\ncircumstances.&nbsp;<\/p>\n<p>There are certain uses with Blobs in OLE controls that use <b>GlobalAlloc<\/b>.<\/p>\n<p>The <b>DEVNAMES<\/b> structure and certain fields of the <b>PRINTDLG <\/b>(contained<br \/>\nin <b>CPrintDialog<\/b>) use global memory handles for backward compatibility<br \/>\nwith 16-bit Windows.<\/p>\n<p>There may be other uses, but the documentation will always tell you if a<br \/>\nglobal handle is needed. Otherwise, avoid them entirely.<\/p>\n<hr>\n<h3><a name=\"LocalAlloc\">Using LocalAlloc<\/a><\/h3>\n<p>Severity: <a href=\"#Poor style\">poor style<\/a><\/p>\n<p>There is no reason to use <b>LocalAlloc<\/b>. This is a throwback for<br \/>\ncompatibility with old Win16 programs. Ignore its existence. The only reason to<br \/>\nuse <b>LocalFree<\/b> is for the buffer that is returned from <b>FormatMessage<\/b>.<br \/>\nThere may be other uses that are mandated, since I have not read or memorized<br \/>\nall 5,000 or so API calls. But unless the use is mandated by an API call, there<br \/>\nis absolutely no reason to consider this as useful.<\/p>\n<hr>\n<h3><a name=\"Array delete\">Doing a delete of an array object without []<\/a><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">potentially fatal<\/a><\/p>\n<p>When you do a delete on an array of objects, it is crucial that you include<br \/>\nthe [] in the syntax, that is, if <b>data<\/b> is an array of objects,<\/p>\n<pre>delete data;    \/\/ <font color=\"#FF0000\">wrong!<\/font>\r\ndelete [] data; \/\/ right<\/pre>\n<p>The problem is that the first form only deletes the space occupied by the<br \/>\narray. The second for deletes the space occupied by the array, but first calls<br \/>\nthe destructors on every object in the array.<\/p>\n<p>For example, consider the class<\/p>\n<pre>class MyData {\r\n    public:\r\n      int x;\r\n      int y;\r\n};<\/pre>\n<p>If I write<\/p>\n<pre>MyData * data = nwe MyData[n];<\/pre>\n<p>then <i>n<\/i> objects are allocated. If I do&nbsp;<\/p>\n<pre>delete data;<\/pre>\n<p>the array is deleted. Everything appears to work. But consider, if I do<\/p>\n<pre>class MyData {\r\n    public:\r\n      int x;\r\n      int y;\r\n      CString s;\r\n};<\/pre>\n<p>The the call<\/p>\n<pre>delete data;<\/pre>\n<p>will delete the space, but the <b>CString<\/b> destructor will not be called<br \/>\non each element. The effect will be a storage leak. If, however, I write<\/p>\n<pre>delete [] data;<\/pre>\n<p>then the destructor <i>is<\/i> called on each element of the array, and proper<br \/>\nobject destruction is done for each contained object. Note that the effect of<br \/>\nfailing to write the <b>delete<\/b> correctly is that the addition of an object<br \/>\nrequiring a destructor will mean the program stops working properly in some way<br \/>\n(usually a memory leak, but it could be more serious), and you won&#8217;t know what<br \/>\nwent wrong.<\/p>\n<hr>\n<h3><a name=\"non-const\">Using non-const static variables in functions<\/a><\/h3>\n<p>Severity: <a href=\"#Deeply suspect\">deeply suspect<\/a> to<br \/>\n<a href=\"#Potentially fatal\">potentially fatal<\/a><\/p>\n<p>By &quot;static&quot; variables here I mean a declaration of the form<\/p>\n<pre>static <i>type<\/i> <i>name<\/i>;<\/pre>\n<p>and all variants, when they appear inside a function. An example is<\/p>\n<pre>int DoSomething()\r\n   {\r\n    static int count = 0;\r\n    ...\r\n    count++;\r\n    }<\/pre>\n<p>This may give the illusion of being modular, but in fact it is a very poor<br \/>\nprogramming technique. I find that this is a technique which is a throwback to<br \/>\nthe more primitive forms of C programming. It is inappropriate in a Windows<br \/>\nprogramming environment. The reasons deal with functions that need to be<br \/>\nreentrant across class instances and functions which could appear in a<br \/>\nmultithreading context.<\/p>\n<p>The worst and most typical form is<\/p>\n<pre>LPCTSTR ConvertToString(SomeType * t)\r\n    {\r\n      static TCHAR result[SOME_SIZE_HERE];\r\n      wsprintf(_T(&quot;%d:%02d\/%d&quot;), t-&gt;seconds \/ 60, t-&gt;seconds % 60, t-&gt;divisor);\r\n      return result;\r\n    }<\/pre>\n<p>A piece of code like this in any program is an invitation to disaster. The<br \/>\nfirst thing I do when I find it is rip it out and replace it with something<br \/>\nsensible. There is no point in wasting time trying to debug a program that is<br \/>\nthis deeply flawed. When I&#8217;m working with MFC, I tend to return <b>CString<\/b><\/p>\n<p>data types, since the allocation is automatically handled.<\/p>\n<p>When would the above code fail? Consider the case<\/p>\n<pre>CString s;\r\ns.Format(_T(&quot;%s and not greater than %s&quot;), CovertToString(t1), ConvertToString(t2));<\/pre>\n<p>Both <b>ConvertToString<\/b> operations use the same buffer and return it, so<br \/>\nby the time the format string is processed, the buffer computed by the<br \/>\nconversion of <b>t2<\/b> is clobbered by the result of the conversion to <b>t1<\/b><\/p>\n<p>(remember that parameters are always evaluated right-to-left).<\/p>\n<p>Consider the case of multithreading, where two threads execute a call to <b>ConvertToString<\/b>.<br \/>\nThe value seen is unpredictable, and on a multiprocessor the string could<br \/>\npotentially change while being read!<\/p>\n<p>The use of <b>const<\/b> static variables is perfectly acceptable, for<br \/>\nexample,&nbsp;<\/p>\n<pre>double ConvertToSomething(double f)\r\n   {\r\n    static const factors[] = {1.0, 1.5, 1.723, 1.891, 1.9843};\r\n    ... do some conversion here, using factors[i] based on \r\n    ... some criterion appropriate\r\n    return result;\r\n   }<\/pre>\n<p>The code of the form<\/p>\n<pre>CString cvMonth(int n)\r\n    {\r\n     static const LPCTSTR names[] = {_T(&quot;Jan&quot;), _T(&quot;Feb&quot;), _T(&quot;Mar&quot;), ...etc };\r\n     return names[n];\r\n    }<\/pre>\n<p>however, is probably a Very Bad Idea since it binds a particular language<br \/>\ninto the source code, which is a losing idea when internationalization is<br \/>\nrequired. You <i>could<\/i> do<\/p>\n<pre>CString cvMonth(int n)\r\n   {\r\n    static const UINT names[] = { IDS_JAN, IDS_FEB, IDS_MAR, ...etc. };\r\n    CString result;\r\n    result.LoadString(names[i]);\r\n    return result;\r\n   }<\/pre>\n<p>But even this is a Bad Idea if you have to deal with any culture that has<br \/>\nmore than 12 months in its year, or whose month index would not correspond to<br \/>\nthe Western European\/American civil conventions that January is the first (zeroth)<br \/>\nmonth. Use the National Language Support APIs, but that&#8217;s a different essay to<br \/>\nbe written at some future time.<\/p>\n<p>There is one exception to this: cached values. A cache keeps a precomputed<br \/>\nvalue, but&#8211;and this is critical&#8211;it has a way of detecting if the cache is<br \/>\ninvalid. You can frequently get nice performance speedups if you use cached<br \/>\nvalues, but here you have to weigh the cost of cache management with the cost of<br \/>\nnot caching. This management includes both the execution costs of determining if<br \/>\nthe cache is valid and the architectural costs imposed if explicit cache<br \/>\ninvalidation is required (and the concomitant costs of failure to invalidate and<br \/>\nusing incorrect data). Here you have to use good judgment, and put lots of<br \/>\nexplicit comments explaining exactly <i>why<\/i> the use of a non-<b>const<\/b><br \/>\nstatic value is a valid thing to do. And even then, I&#8217;d be more inclined to keep<br \/>\nthe cache in a member variable of a class that was involved in the computation,<br \/>\nrather than in a static variable. The only reason to use static variables is if<br \/>\nthe cache maintains validity across multiple objects.<\/p>\n<hr>\n<h3><a name=\"Using new without any reason to\">Using new without any reason to<\/a><\/h3>\n<p>For some reason, people use <b>new<\/b> when there is absolutely no reason to<br \/>\ndo so. The most common failure of thinking is when it comes to passing pointers<br \/>\nto objects. For example, if I have an API that requires a parameter <b><br \/>\nSOMEDATATYPE<\/b>&nbsp;<b>*<\/b>, the solution is obvious:<\/p>\n<pre>    SOMEDATATYPE data;\r\n    SomeAPI(&amp;data);<\/pre>\n<p>This has not stopped programmers from thinking that the type of the argument<br \/>\nhas to match the type of a variable, so they will do<\/p>\n<pre>    SOMEDATATYPE * data;\r\n    data = new SOMEDATATYPE;\r\n    SomeAPI(data);\r\n    ... use it\r\n    delete data;<\/pre>\n<p>It is hard to imagine why the second form could ever be imagined to make<br \/>\nsense. It introduces a gratuitous concept, memory allocation, to a place where<br \/>\nmemory allocation is not needed, and requires a corresponding <b>delete<\/b>.<br \/>\nThis not only adds intellectual baggage, it obscures the purpose of the code,<br \/>\nand introduces two possibilities for error. The first is that the <b>new<\/b><br \/>\nfailed (note the lack of any check for its success!) and the second is that in<br \/>\nthe section called &quot;use it&quot; that the code gets very long, and someone puts, in a<br \/>\nlater modification, a <b>return&nbsp;FALSE<\/b> or some similar construct into the<br \/>\ncode which bypasses the <b>delete<\/b>, resulting in a storage leak.<\/p>\n<p>Another example is to create a member variable for some type of window, e.g.,<br \/>\na dynamically-created <b>CButton<\/b>:<\/p>\n<pre>class whatever : public CFormView {\r\n    ...\r\n    protected:\r\n        CButton * mybutton;\r\n};<\/pre>\n<p>then in the code do<\/p>\n<pre>    mybutton = new CButton;\r\n    mybutton-&gt;Create(...stuff here...);<\/pre>\n<p>This has the same problem as above. This introduces a gratuitous need for a<br \/>\nconcept that has no relevance, allocation; it requires that you remember to put<br \/>\ninto the constructor an assignment <\/p>\n<pre>    mybutton = NULL;<\/pre>\n<p>and in the destructor<\/p>\n<pre>    delete mybutton;<\/pre>\n<p>all of which is pointless intellectual overhead. Instead, do <\/p>\n<pre>    protected:\r\n        CButton mybutton;<\/pre>\n<p>and then you can do <\/p>\n<pre>    mybutton.Create(...stuff here...);<\/pre>\n<p>Note that concepts such as initialization of the pointer, destruction of the<br \/>\nobject, and the use of <b>new<\/b> are replaced by a trivial concept: declaring a<br \/>\nvariable. <i>There is virtually no reason to allocate a <b>CWnd<\/b>-derived<br \/>\nclass dynamically when its extent is the extent of the parent class.<\/i><\/p>\n<p>Just about the only place where you do this dynamically is to allocate a <b><br \/>\nCDialog&nbsp;*-<\/b>derived object for a modeless dialog.<\/p>\n<p>Another example is &quot;but what if I need an array of integers?&quot; What if you do?<br \/>\n<b>CArray<\/b> or <b>std::vector<\/b> exist, and work quite well. For example,<br \/>\nconsider the case where you need an array of integers which represent the<br \/>\nselected items in a multi-select listbox:<\/p>\n<pre>    CArray&lt;int, int&gt;selections;\r\n    int n = c_MyListBox.GetSelCount();\r\n    selections.SetSize(n);\r\n    c_MyListBox.GetSelItems(n, selections.GetData());<\/pre>\n<p>works nicely, and has the advantage that you don&#8217;t need to remember to call<br \/>\n<b>delete<\/b>.<\/p>\n<p>There are lots of valid reasons to use <b>new<\/b>. Foremost among them is<br \/>\npassing information across thread boundaries. Information to be passed is put<br \/>\ninto a heap-allocated object, and a pointer to that object is passed from one<br \/>\nthread to another. When the receiving thread is finished with the object, it<br \/>\ncalls <b>delete<\/b>. <\/p>\n<hr>\n<h3><a name=\"Dynamic Controls\">Creating Controls Dynamically<\/a><\/h3>\n<p>Severity: <a href=\"#Deeply suspect\">deeply suspect<\/a>, <a href=\"#Poor style\"><br \/>\npoor style<\/a> (unless there really is no alternative!)<\/p>\n<p>There are <i>lots <\/i>of valid reasons for creating controls dynamically. One correspondent<br \/>\npointed out that he had to create controls based on an XML description. I&#8217;ve<br \/>\ndone them from database schemata. But 99% of the time I see someone creating a<br \/>\ncontrol dynamically, they&#8217;re doing it for the wrong reasons. And sometimes when<br \/>\nthey do it, they do it in the wrong way.<\/p>\n<p>It is rare to need to create a control dynamically (in spite of the fact<br \/>\nthere are lots of valid reasons, they only rarely apply). However, it is also<br \/>\nunnecessary in general to do a <b>new<\/b> to allocate an object to reference the<br \/>\ncontrol. I commonly see people doing things like<\/p>\n<pre>BOOL CMyDialog::OnInitDialog()\r\n   {\r\n    CDialog::OnInitDialog();\r\n    if(sometestorother)\r\n       { \/* we could stop *\/\r\n        <font color=\"#FF0000\">CButton<\/font> <font color=\"#FF0000\">stop = new CButton;\r\n        CRect r(175, 54, 205, 65);\r\n        stop-&gt;Create(&quot;Stop&quot;, BS_PUSHBUTTON, r, this, IDC_STOP);<\/font>\r\n       } \/* we could stop *\/<\/pre>\n<p>Just about every line in the above code is about as wrong as you can get. The<br \/>\nproblems are<\/p>\n<ul>\n<li>You don&#8217;t need to do a <b>new<\/b> &nbsp;<\/li>\n<li>You would have to do a <b>delete<\/b> but this code stores the pointer in a<br \/>\n    local variable so the window could not be deleted<\/li>\n<li>The magic constants shown are complete nonsense<\/li>\n<li>It only works for 8-bit English applications<\/li>\n<li>It actually <i>assumes<\/i> the the <b>Create<\/b> operation works!<\/li>\n<\/ul>\n<p>Key here is that <i>none<\/i> of these lines are required, or are even<br \/>\ncorrect. I would simply create the control in the Dialog editor, size it and<br \/>\nplace it where I wanted it, and then do<\/p>\n<pre>BOOL CMyDialog::OnInitDialog()\r\n   {\r\n    CDialog::OnInitDialog();\r\n    c_Stop.ShowWindow(sometestorother ? SW_SHOW : SW_HIDE);<\/pre>\n<p>Note how much simpler and cleaner this is. I don&#8217;t have to compute a<br \/>\nposition, I don&#8217;t have to allocate anything, I don&#8217;t have to delete anything,<br \/>\nand I don&#8217;t have to do a <b>Create<\/b>.&nbsp;<\/p>\n<p>If I had to create a control at runtime, there is no reason to do a <b>new<\/b><br \/>\nif there is not some dynamic quantity being created. Just declare yourself,<br \/>\noutside the scope of the magic AFX comments, an appropriate variable<\/p>\n<pre>CMyCustomControl ctl;<\/pre>\n<p>Don&#8217;t do a <b>new<\/b> unless there is a <i>compelling<\/i> reason to do so<br \/>\n(there can be, but most of the instances I&#8217;ve seen where <b>new<\/b> is used to<br \/>\ncreate a control variable are just a waste of conceptual energy).<\/p>\n<p>When you need to create the control, just make sure your custom control has a<br \/>\n<b>Create<\/b> method, and write<\/p>\n<pre>CString caption;\r\ncaption.LoadString(IDS_STOP);\r\nVERIFY(ctl.Create(caption,and,parms,you,want,here));<\/pre>\n<p>To create a control based on a custom window class, you can select the<br \/>\n&quot;custom control&quot; (the little human head icon) from the toolbox. Use it<br \/>\nto place the control. Specify the class name of the control class in the <b>Properties<\/b><br \/>\nbox. Select the desired styles. The problem with the styles is that you can&#8217;t<br \/>\njust use symbolic names like <b>WS_VISIBLE<\/b>, which is a real pain; you have<br \/>\nto go into <b>winuser.h<\/b> and figure out the correct hex constants to use.<br \/>\nSigh. Make sure you have registered the window class before you try to create<br \/>\nthe window. You may do this in the <b>InitInstance<\/b> handler for a<br \/>\ndialog-based app, or in the constructor for a <b>CDialog-<\/b> or <b>CFormView<\/b>-derived<br \/>\nclass.&nbsp;Or see my essay on <a href=\"selfregister.htm\">self-registering<br \/>\nclasses<\/a>.<\/p>\n<p>I use <b>VERIFY<\/b> to make sure that if there were an error, I will see it<br \/>\nat the time the creation is done, instead of having some other part of my<br \/>\nprogram fail much later for reasons I will have to work hard to understand. In<br \/>\nsome cases I might store the result and take other action, but in most cases,<br \/>\ncreation failures represent coding errors which, once fixed, no longer exist.<br \/>\nThis catches the failure early.<\/p>\n<h4>Hints: making dynamic creation easy<\/h4>\n<p>Suppose I wanted to create a pushbutton. I would know that, for example, its<br \/>\nleft edge, right edge, top edge, and\/or bottom edge (choose at least one<br \/>\nhorizontal and one vertical) would have to line up in some way with some other<br \/>\ncontrol. Or be a certain percentage distance from a left, right, top, and\/or<br \/>\nbottom of the window.<\/p>\n<p>Rather than compute the button size, which must be in pixels, based on some<br \/>\ncriterion, or trying to mess with Dialog Box Units, which are a waste of<br \/>\nintellectual effort, I would use one of several tricks.<\/p>\n<p>When I had to do this in a product I delivered, I created a form which had<br \/>\nseveral hidden controls: a combo box, a radio button, a check box, a static<br \/>\nlabel, and an edit control. I created these as disabled, invisible controls. I<br \/>\ndid not have space on the form to put them (the entire body of the form was a<br \/>\ngiant ListBox that contained these controls inside it), so I simply made the ListBox<br \/>\na little smaller vertically and resized it in the <b>OnInitialUpdate<\/b><br \/>\nhandler of the form. Thus it overlapped the invisible controls, but I could<br \/>\nstill see them in the dialog editor (hint: if you <i>ever<\/i> discover you are<br \/>\ncreating physically overlapping controls, <i>rethink what you are doing<\/i>.<br \/>\nThere is <i>always<\/i> a better way. I&#8217;ll trade off more complex code for ease<br \/>\nof long-term maintenance any day!<\/p>\n<p>When I needed to create an Edit control, I had a variable, <b>c_EditPrototype<\/b>,<br \/>\nwhich got the value of the edit control that I put on the dialog. I wrote<br \/>\nsomething along these lines:<\/p>\n<pre>void CMyForm::CreateEdit(int n)\r\n   {\r\n    \/\/ Create an edit control on line <i>n<\/i> of the listbox\r\n    CRect r;\r\n    c_EditPrototype.GetWindowRect(&amp;r);\r\n    CRect line;\r\n    c_Data.GetItemRect(&amp;line);\r\n    int left = ...complex computation of left edge of edit control;\r\n    CRect edit(left, line.top, left + r.Width(), line.top + r.Height());\r\n    CEdit * ctl = new CEdit;\r\n    ctl-&gt;Create(<i>styles<\/i>, edit, &amp;c_Data, controlid++);\r\n    ...lots more stuff here, including saving the CEdit * for later deletion\r\n   }<\/pre>\n<p>One key insight here is that I did not have to worry about the font size or<br \/>\nscreen resolution. The edit control prototype was the width desired (all edit<br \/>\ncontrols would be the same width), the height was automatically set when the<br \/>\ndialog was created, taking into account the font size, resolution, etc., so all<br \/>\nI had to do was copy them.&nbsp;<\/p>\n<p>The buttons were a bit trickier; what I did was create a button with no<br \/>\ncaption text. This gave me my minimum width; I then added <b>GetTextExtent<\/b><br \/>\npixels to that to get the new desired size.<\/p>\n<p>Bottom line, <i>be lazy<\/i>. Let the system do as much for you as it<br \/>\ncan.&nbsp;<\/p>\n<p>If I had wanted a caption, I would have stored the caption in the <b>STRINGTABLE<\/b><br \/>\nand loaded it dynamically. I would never hard-code English text into a product<br \/>\nprogram. If I wanted a button with a non-language caption, I would create it as<\/p>\n<pre>c_Button.Create(_T(&quot;&lt;&lt;&quot;), BS_PUSHBUTTON, r, this, IDC_REVERSE);<\/pre>\n<p>Note the use of <b>_T(&nbsp;)<\/b> around the string constant so it is<br \/>\nUnicode-aware.<\/p>\n<p><b>Positioning<\/b><\/p>\n<p>Sometimes it is easy. Suppose I need to create a custom control centered in a<br \/>\nform, just above another control. We have a desired width and height.<\/p>\n<pre>CRect client;\r\nGetClientRect(&amp;client);\r\n\r\nCRect below;\r\nc_WhateverControl.GetWindowRect(&amp;below); \/\/ the control below the one we want\r\nScreenToClient(&amp;below); \/\/ convert to client coordinates\r\ngap = 2 * ::GetSystemMetrics(SM_CYEDGE); \/\/ allow nice gap between\r\n\r\nint left = (client.Width() - width) \/ 2;\r\nCRect ctlrect(left, below.top - height - gap,\r\n               left + width, below.top - gap, this, ctlid);<\/pre>\n<p>You can compute all the geometry you want, but if constants appear in any<br \/>\ncontext other than multipliers or divisors, you are in trouble. Note that I even<br \/>\ncompute the gap based on the screen driver&#8217;s opinion of the height of the ideal<br \/>\n3-D horizontal edge.<\/p>\n<p>If you know where you want it, and how big it will be, you can simply create,<br \/>\nin the dialog editor, a static control, such as a frame or rectangle. Mark it as<br \/>\ninvisible. Change its ID from <b>IDC_STATIC<\/b> to something useful. Create a<br \/>\ncontrol variable for it. For example, I might call it <b>IDC_CUSTOM<\/b> and the<br \/>\nvariable <b>c_CustomFrame<\/b>.<\/p>\n<pre>CRect w;\r\nc_CustomFrame.GetWindowRect(&amp;w);\r\nScreenToClient(&amp;w);\r\nc_WhateverControl.Create(styles, w, this, ctlid);\r\nc_CustomFrame.DestroyWindow(); \/\/ no longer need frame<\/pre>\n<p>Note that there is <i>no<\/i> computation of the size; the size has already<br \/>\nbeen computed for me by the dialog handler when it instantiated the static<br \/>\ncontrol, and I am creating a custom control in the same area.<\/p>\n<hr>\n<h3><a name=\"Using hardwired constants for any size or position\">Using hardwired<br \/>\nconstants for any size or position<\/a><\/h3>\n<p>Severity: <a href=\"#Serious\">serious<\/a><\/p>\n<p>It is a common practice to want to rearrange controls on a dialog at run<br \/>\ntime, for example, when the dialog is resized. An unfortunate characteristic of<br \/>\nsuch code is that it tends to include hardwired constants, which is almost<br \/>\nalways an unrecoverable flaw.<\/p>\n<p>This is because dialogs are always expressed in terms of <i>Dialog Box Units<\/i>,<br \/>\nwhich are an abstract coordinate system. When a dialog is instantiated, the<br \/>\nsystem &quot;realizes&quot; the dialog box by computing a function based on the<br \/>\ndefault system font. From that point on, everything is in terms of pixels. For a<br \/>\nvery high resolution (e.g., 1600&nbsp;\u00c3\u20141200) the dialog may take many more pixels<br \/>\nthan if the display is running at some lower (e.g., 800&nbsp;\u00c3\u2014&nbsp;600), because it tries<br \/>\nto keep an approximately same-size-on-the-screen effect of a given dialog. The<br \/>\ndownside is that any attempt to use a hardwired constant is doomed from the<br \/>\nstart..<\/p>\n<p>The proper method is to use one of the basic resolution-sensitive parameters<br \/>\nof the system to scale the dimensions properly. Two of the key parameters are<br \/>\nthe border size and the resize border size. For example, I might choose to<br \/>\nseparate a set of buttons by a multiple of the resize border size. In a very<br \/>\nhigh resolution, this size may be doubled over what it is at a lower resolution.<br \/>\nUseful computations I include in my positioning code might be<\/p>\n<pre>UINT vsep = 3 * ::GetSystemMetrics(SM_CXBORDER);\r\nUINT colsep = 2 * ::GetSystemMetrics(SM_CXEDGE);<\/pre>\n<p>The most useful values I have found for <b>::GetSystemMetrics<\/b> that are<br \/>\nhandy to know about are shown in the table below. However, there are many other<br \/>\nparameters which can be interesting.<\/p>\n<table border=\"1\" width=\"100%\">\n<tr>\n<td width=\"32%\" valign=\"top\"><b>SM_CXBORDER<br \/>\n      SM_CYBORDER<\/b><\/td>\n<td width=\"68%\" valign=\"top\">Width and height, in pixels, of a window<br \/>\n      border. This is equivalent to the <b>SM_CXEDGE<\/b> value for windows with<br \/>\n      the 3-D look.<\/td>\n<\/tr>\n<tr>\n<td width=\"32%\" valign=\"top\"><b>SM_CXEDGE<br \/>\n      SM_CYEDGE<\/b><\/td>\n<td width=\"68%\" valign=\"top\">Dimensions, in pixels, of a 3-D border. These<br \/>\n      are the 3-D counterparts of <b>SM_CXBORDER<\/b> and <b>SM_CYBORDER<\/b><\/td>\n<\/tr>\n<tr>\n<td width=\"32%\" valign=\"top\"><b>SM_CXFIXEDFRAME,<br \/>\n      SM_CYFIXEDFRAME<\/b><\/td>\n<td width=\"68%\" valign=\"top\">Thickness, in pixels, of the frame around the<br \/>\n      perimeter of a window that has a caption but is not sizable. <b>SM_CXFIXEDFRAME<\/b><br \/>\n      is the heightof the horizontal border and <b>SM_CYFIXEDFRAME<\/b> is the<br \/>\n      width of the vertical border.<\/td>\n<\/tr>\n<tr>\n<td width=\"32%\" valign=\"top\"><b>SM_CXSIZEFRAME,<br \/>\n      SM_CYSIZEFRAME<\/b><\/td>\n<td width=\"68%\" valign=\"top\">Thickness, in pixels, of the sizing border<br \/>\n      around the perimeter of a window that can be resized. <b>SM_CXSIZEFRAME<\/b><br \/>\n      is the width of the horizontal border, and <b>SM_CYSIZEFRAME<\/b> is the<br \/>\n      height of the vertical border.<\/td>\n<\/tr>\n<tr>\n<td width=\"32%\" valign=\"top\"><b>SM_CXHTHUMB<\/b><\/td>\n<td width=\"68%\" valign=\"top\">Width, in pixels, of the thumb box in a<br \/>\n      horizontal scroll bar.<\/td>\n<\/tr>\n<tr>\n<td width=\"32%\" valign=\"top\"><b>SM_CYVTHUMB<\/b><\/td>\n<td width=\"68%\" valign=\"top\">Height, in pixels, of the thumb box in a<br \/>\n      vertical scroll bar.<\/td>\n<\/tr>\n<tr>\n<td width=\"32%\" valign=\"top\"><b>SM_CYCAPTION<\/b><\/td>\n<td width=\"68%\" valign=\"top\">Height, in pixels, of a normal caption area.<\/td>\n<\/tr>\n<tr>\n<td width=\"32%\" valign=\"top\"><b>SM_CXVSCROLL,<br \/>\n      SM_CYVSCROLL<\/b><\/td>\n<td width=\"68%\" valign=\"top\">Width, in pixels, of a vertical scroll bar; and<br \/>\n      height, in pixels, of the arrow bitmap on a vertical scroll bar.<\/td>\n<\/tr>\n<\/table>\n<p>&nbsp;In those rare cases where you may need to create controls dynamically,<br \/>\nhardwiring any integer value for the width or height is uniformly a blunder. I<br \/>\nhave found the most convenient way to create controls dynamically is to lay down<br \/>\na &quot;prototype&quot; control on the dialog. I mark this control as invisible,<br \/>\nand create a control member variable for it. Then, for example, if I need to<br \/>\ncreate a control at runtime I use the dimensions of this control to determine<br \/>\nthe dimensions of the control I want to create, most often the height.<\/p>\n<pre>CStatic c_PrototypeStatic;   \/\/ declared in the class by ClassWizard<\/pre>\n<pre>\/\/...create the control at position x,y holding text 'caption'\r\nCRect r;\r\nc_PrototypeStatic.GetWindowRect(&amp;r);\r\nScreenToClient(&amp;r);\r\nCClientDC dc(&amp;c_PrototypeStatic);\r\nint width = dc.GetTextExtent(caption).cx;\r\nwidth += 2 * ::GetSystemMetrics(SM_CXEDGE);\r\nr.right = r.left + width;\r\n\r\nCRect w(x, y, x + r.Width(), y + r.Height());\r\n...Create(caption, SS_LEFT, w, this, IDC_STATIC);<\/pre>\n<p>Note that I did not show anything to the left of the <b>Create<\/b> method<br \/>\nbecause there are lots of ways I could create a window as simply calling<\/p>\n<pre>CStatic * wnd = new CStatic;\r\nwnd-&gt;Create(...);<\/pre>\n<p>or have an array&nbsp;<\/p>\n<pre>wnd[i] = new CStatic;\r\nwnd[i]-&gt;Create(...);<\/pre>\n<p>or have a variable declared in the class and write<\/p>\n<pre>c_MyLabel.Create(...);<\/pre>\n<p>Here&#8217;s another trick I use a lot: I need, for whatever reason, to create a<br \/>\nwindow at runtime at a specific location on a dialog. Often this is a custom<br \/>\ncontrol of some sort. To get it properly positioned on the dialog, I do not ever<br \/>\nrely on coordinates that I &quot;wire in&quot;. Instead, I place an invisible <b>CStatic<\/b><br \/>\ncontrol with an ID other than <b>IDC_STATIC<\/b> on the dialog, and use its<br \/>\ncoordinates to create my desired custom window. For example<\/p>\n<pre>CStatic c_Frame; \/\/ created by ClassWizard\r\n\r\nCMyControl c_Whatever; \/\/ added by hand in the protected area\r\n\r\nBOOL CMyDialog::OnInitDialog()\r\n   {\r\n    ... lots of stuff here...\r\n    CRect r;\r\n    c_Frame.GetWindowRect(&amp;r);\r\n    ScreenToClient(&amp;r);\r\n    UINT id = c_Frame.GetDlgCtrlId();\r\n    c_Whatever.Create(r, this, id);\r\n    c_Frame.DestroyWindow();\r\n    ... more stuff here...\r\n   } \/\/ CMyDialog::OnInitDialog<\/pre>\n<p>Note some tricks here. I can actually reuse the control ID because I destroy<br \/>\nthe static window (although this is not actually necessary, I find it cleaner).<br \/>\nThe <b>Create<\/b> method shown here is the <b>Create<\/b> method I have written<br \/>\nfor my own control. Your Mileage May Vary and you may have additional<br \/>\nparameters.<\/p>\n<p>Another time I use this trick is when I want to limit the amount the user can<br \/>\nresize a resizable dialog. What I will do is create an invisible static control<br \/>\nthat represents the minimum size. This is much cleaner than picking some control<br \/>\nto serve the purpose, because if you rearrange the controls the control you<br \/>\noriginally selected may no longer be the rightmost or bottommost.&nbsp;<\/p>\n<p>To create an <b>OnGetMinMaxInfo<\/b> handler, you either have to add it by<br \/>\nhand or go to the Class tab in the ClassWizard and change the type from dialog<br \/>\nto general <b>CWnd<\/b>. It should have been obvious to Microsoft that a resizable<br \/>\ndialog would need this (they have the style flags available to determine this)<br \/>\nbut this is one of the many defects of ClassWizard.<\/p>\n<pre>void CMyDialog::OnGetMinMaxInfo(MINMAXINFO * lpMMI)\r\n   {\r\n    CRect r;\r\n    c_Frame.GetWindowRect(&amp;r);\r\n    ScreenToClient(&amp;r);\r\n    lpMMI.ptMinTrackSize.x = r.right;\r\n    lpMMI.ptMinTrackSize.y = r.bottom;\r\n   }<\/pre>\n<p>Because I have the frame to reference, if I add new controls that I don&#8217;t<br \/>\nwant covered on a resize, I only have to adjust the size of the hidden frame.<\/p>\n<p>However, note that at all times I have never, ever once used a hardwired<br \/>\nconstant to determine either the position or the size of any control, or other<br \/>\ndistance, on the dialog.<\/p>\n<hr>\n<h3><a name=\"Using hardwired constants for control IDs\">Using hardwired<br \/>\nconstants for control IDs<\/a><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">potentially (usually, when small<br \/>\nvalues are used) fatal<\/a><\/p>\n<p>It is frequently useful, and sometimes necessary, to be able to create<br \/>\ncontrols at run time. This is a practice which <i>ought<\/i> to be avoided.<br \/>\nTypical silly reasons are largely similar to &quot;I only need the progress<br \/>\ncontrol when I&#8217;m doing the [read, write, computation]&quot;. This is a reason so<br \/>\nsilly that I cannot imagine why anyone would ever think it made sense. It is so<br \/>\ntrivial to hide a control when you don&#8217;t need it (and even create it without the<\/p>\n<p><b>Visible<\/b> property checked) and show it when you need it that this never<br \/>\nmakes sense. It is usually compounded by the tendency to <a href=\"#Using hardwired constants for any size or position\">hardwire<br \/>\ncontrol coordinates<\/a>, which is even less excusable. An even sillier excuse is<br \/>\n&quot;Well, if I create it in the dialog editor and then hide it, <i>it takes up<br \/>\nspace<\/i>&quot;. Yes, and the price of gasoline in downtown Pittsburgh on<br \/>\n18-Mar-03 was $1.65<sup>9<\/sup>\/<sub>10<\/sub>. That is about as relevant to the<br \/>\ndiscussion. People who talk this way act as if the infinitesimal amount of space<br \/>\nrequired to hold the window information <i>actually matters<\/i>. In fact, the <i>code<\/i><br \/>\nrequired to create and manage the window probably takes up more space! This is<br \/>\nanother case of &quot;optimizing&quot; the wrong parameter, with no<br \/>\njustification whatsoever.<\/p>\n<p>A typical sort of insanity tends to look like<\/p>\n<pre>m_progressbar = new CProgressCtrl;\r\nm_progressbar-&gt;Create(...., 1);<\/pre>\n<p>This embodies at least two serious blunders. The use of a dynamically-created<br \/>\n<b>CProgressCtrl<\/b> is another <a href=\"#Dynamic Controls\">silly idea<\/a>. You<br \/>\ncould create a <b>CProgressCtrl<\/b> variable, <i>not<\/i> a <b>CProgressCtrl&nbsp;*<\/b>,<br \/>\nand it would work just as well. Without involving the additional complexity of<br \/>\nthe allocation, and necessitating the corresponding <b>delete<\/b>.<\/p>\n<p>But why create the control at all? Place it on the dialog in the dialog<br \/>\neditor! You get a nice control ID already assigned, you can use the ClassWizard<br \/>\nto create a binding to a control variable. Just uncheck the <b>Visible<\/b><br \/>\nattribute. Then when you need it, replace the complex lines shown above with a<br \/>\nsimple<\/p>\n<pre>c_progressbar.ShowWindow(SW_SHOW);<\/pre>\n<p>when done with it, do a <b>ShowWindow<\/b> with <b>SW_HIDE<\/b>.<\/p>\n<p>Now, when it comes to using hardwired numbers, note the use of the number<br \/>\n&quot;1&quot;. There is no explanation of why so many people choose the number<\/p>\n<p>&quot;1&quot;, but in a dialog this is fatal. The control which is the OK button<br \/>\nhas ID <b>IDOK<\/b>, which a quick inspection of the header files will show is ID<br \/>\nnumber 1. Hence, most attempts to bind the control will fail with <b>ASSERT<\/b><br \/>\nfailures when the binding is tried, because the control with ID 1 is already<br \/>\nassigned.<\/p>\n<p>Typically, for most of us when creating controls, we pick a range of integers<br \/>\nin the range 10000 to 32767. Most importantly, we use a <b>#define<\/b> to define<br \/>\nthe base of this range, so if there is a conflict for some reason, it is trivial<br \/>\nto compensate for it. The reason for the choice of values is that the dialog<br \/>\neditor tends to assign much smaller numbers, and the values in the range greater<br \/>\nthan 32767 would often result in a serious conflict with the existing Microsoft<br \/>\nmenu item ranges.<\/p>\n<hr>\n<h3><a name=\"Using GetDlgItem\">Using GetDlgItem<\/a><\/h3>\n<p>Severity: <a href=\"#Poor style\">poor style<\/a><\/p>\n<p>This is hardly ever necessary. It is certainly not necessary for getting (as<br \/>\nsome have argued with me) the window reference for a control. Just use the<br \/>\ndialog editor to create a control variable. I discuss this in depth in my <a href=\"getdlgitem.htm\">companion<br \/>\nessay<\/a>. Key here is that if you subclass a control later, and override one or<br \/>\nmore of its built-in methods, <b>GetDlgItem<\/b> guarantees that your program<br \/>\nwill stop behaving correctly.&nbsp;<\/p>\n<p>There is rarely an excuse for using it; I write perhaps one a year, and<br \/>\nconsider very carefully the alternatives before doing it.<\/p>\n<hr>\n<h3><a name=\"Using UpdateData\">Using UpdateData<\/a><\/h3>\n<p>Severity: <a href=\"#Poor style\">poor style<\/a><\/p>\n<p>This is one of those ideas so bad that if it hadn&#8217;t already been invented,<br \/>\nnobody would be dumb enough to invent it. It is based on the illusion that you<br \/>\nwant memory variables to be exact replications of control state. We all know<br \/>\nfrom basic design principles that replicating information is usually fatal<br \/>\nunless you are extremely careful about how you manage the state. My experience<br \/>\nwith <b>UpdateData<\/b> was that I found programs harder to write, harder to<br \/>\ndebug, and harder to maintain than programs that didn&#8217;t use it. Almost every<br \/>\ntime I get a dialog that has failure modes such as inconsistent control<br \/>\nbehavior, incorrect results depending on what order controls are used in, and<br \/>\nsimilar problems, I look for <b>UpdateData<\/b>. I find it. I discover the<br \/>\nprogrammer was clueless as to how to use it in a way that would guarantee these<br \/>\nproblems would not exist, which is not surprising given how poorly designed it<br \/>\nis. So I just rewrite the code to eliminate it (see my essays on <a href=\"updatedata.htm\">Avoiding<br \/>\nUpdateData<\/a>, <a href=\"getdlgitem.htm\">Avoiding GetDlgItem<\/a>, and <a href=\"controls.htm\">Dialog<br \/>\nControl Control Management<\/a>). At that point the problems simply disappear.<\/p>\n<hr>\n<h3><a name=\"Writing an OnCommand handler\">Writing an OnCommand handler<\/a><\/h3>\n<p>Severity: <a href=\"#Poor style\">poor style<\/a>,<br \/>\n<a href=\"#Potentially Harmful\">potentially harmful<\/a>,<br \/>\n<a href=\"#Potentially fatal\">potentially fatal<\/a><\/p>\n<p>I have not encountered any situation in which this is a valid approach to<br \/>\nsolving any problem. In all cases I have seen it, it is someone who doesn&#8217;t<br \/>\nunderstand either Windows or MFC trying to do something that is much more easily<br \/>\n(and often correctly) done by using normal MFC message dispatching. In eight<br \/>\nyears of MFC programming, I have only ever written on <b>OnCommand<\/b> handler,<br \/>\nand that was to investigate how <b>OnCommand<\/b> works to explain command<br \/>\nrouting. Every example I have found in code, newsgroup postings, etc. was the<br \/>\nresult of a beginning programmer being totally clueless. Some if this code<br \/>\npersists for years, confusing the next maintainer who has no idea how to modify<br \/>\nthe code.&nbsp;The only solution is to rip this code out and replace it with<br \/>\nsomething that makes sense.<\/p>\n<hr>\n<h3><a name=\"Writing a PreTranslateMessage handler\">Writing a<br \/>\nPreTranslateMessage handler<\/a><\/h3>\n<p>Severity: <a href=\"#Deeply suspect\">deeply suspect<\/a><\/p>\n<p>This is an overused and usually inappropriately-used technology. Many<br \/>\nprogrammers use it as a substitute for doing proper subclassing of events. There<br \/>\nare many legitimate reasons to use it, but they are far and away overshadowed by<br \/>\ninappropriate misuse. Generally, the severe warning signs of misuse are<\/p>\n<ul>\n<li>Subclass avoidance\n<ul>\n<li>There is a test for a specific control ID in the <b>PreTranslateMessage<\/b><br \/>\n    code<\/li>\n<li>The control has not been subclassed<\/li>\n<li>The message type is a message that could be handled by subclassing the<br \/>\n    control<\/li>\n<\/ul>\n<\/li>\n<li>Testing for <b>Enter<\/b> or <b>Escape<\/b> keys in a dialog to avoid<br \/>\n  closing the dialog (see my <a href=\"dialogapp.htm\">essay on dialog apps<\/a><br \/>\n  for a cleaner solution!)<\/li>\n<\/ul>\n<p>Appropriate uses include testing for mouse and keyboard events without<br \/>\nattaching those to a specific control ID (for example, handling F1 help),<br \/>\nhandling complex tasks which MFC interferes with, such as editing labels in a<br \/>\ntree control contained in a property page (the <b>Enter<\/b> key to terminate<br \/>\nlabel editing will also close the property sheet if you don&#8217;t do the override),<br \/>\nand, <i>within a subclass<\/i> handling messages sent to that control.<\/p>\n<hr>\n<h3><a name=\"Writing an OnCtlColor handler\">Writing an OnCtlColor handler<\/a><\/h3>\n<p>Severity: (exceptionallly) <a href=\"#Poor style\">poor style<\/a><\/p>\n<p>This seems like it would be a legitimate activity. It rarely is. <b><\/p>\n<p>OnCtlColor<\/b> is part of the parent class, and therefore suggests that somehow<br \/>\nthe parent class should know what color to use for a child window. This is a<br \/>\nthrowback to the days of early 16-bit Windows programming, when the paradigms<br \/>\nhad not been properly thought out. It violates every sensible definition of<br \/>\nmodularity that exists. I have no idea how a parent control can know how a child<br \/>\ncontrol should paint itself. Years ago, I started writing reflected <b><br \/>\nWM_CTLCOLOR<\/b> handlers for child classes, and it seemed much saner. All I did<br \/>\nwas take the incoming<b> WM_CTLCOLOR<\/b> message and send it to the window whose<br \/>\nhandle was provided.<i> That<\/i> window handled the coloring. <b><i>&nbsp;<\/i><\/b>I<br \/>\nhave only seen one sensible use of <b>OnCtlColor<\/b>, when the programmer wanted<br \/>\nto change the color of <i>every<\/i> child control in a dialog (and I question<br \/>\nwhy this was a valid thing to do). The <i>correct<\/i> approach is to subclass<br \/>\nthe control, and use the <i>reflected<\/i> <b>WM_CTLCOLOR_<i>xxx<\/i><\/b> message<br \/>\nby subclassing the child control and creating an <b>=WM_CTLCOLOR<\/b> <\/p>\n<p>reflected-message handler in that subclass. MFC<br \/>\nwill then route the message to the child class, which is where the decisions<br \/>\nbelong. Key warning sign: there is a test for both the control message type and<br \/>\na specific control ID in the body of the handler.<\/p>\n<hr>\n<h3><a name=\"Control Management\">Control Management<\/a><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">potentially fatal<\/a> (when done<br \/>\npoorly, that is, distributed throughout the dialog)<\/p>\n<p>If you do the same computation in two places, pretty soon you won&#8217;t have the<br \/>\nsame computation.<\/p>\n<p>This is why we use subroutines.<\/p>\n<p>Unfortunately, this knowledge seems to be lost on programmers who try to<br \/>\nmanipulate controls in a <b>CDialog-<\/b> or <b>CFormView<\/b>-derived class.<\/p>\n<p>I blame some of this on Charles Petzold, because I learned from his Win16 book<br \/>\nback in 1989 or so, and<br \/>\nit teaches a number of horrendously bad Windows programming habits, which I then<br \/>\nhad to break. Essentially, what I did was say &quot;There is something wrong<br \/>\nwith this; how do I do this right in Windows?&quot; and it took me a couple<br \/>\nyears to get the paradigms right.&nbsp;<\/p>\n<p>So I wrote an essay on how I do dialog control management in dialogs and<br \/>\n<b>CFormView<\/b>s. It works, it is highly effective, and it is the way I have written<br \/>\ncontrol management for about eight years. It consolidates all the control logic<br \/>\nin one place. It would have been nicer if Microsoft had given us <b>ON_UPDATE_COMMAND_UI<\/b><br \/>\nhandlers in dialogs, an extension that seems blindingly obvious, but they<br \/>\ndidn&#8217;t. I have written an <a href=\"controls.htm\">essay<\/a> on this<br \/>\ntechnique.&nbsp;<\/p>\n<p>Bottom line: when I get a dialog that malfunctions in terms of enabling, I<br \/>\nsimply look for all instances of <b>ShowWindow<\/b> and <b>EnableWindow<\/b>, and<br \/>\nthen consolidate them in one function I call <b>updateControls<\/b>. I was given<br \/>\none app which updated several controls, in 23 different places, using 6<br \/>\ndifferent algorithms, <i>all of which were wrong!&nbsp; <\/i>Furthermore,<br \/>\ndepending on what the user had most recently done, controls that should have<br \/>\nbeen enabled remained disabled, or controls which should have been disabled<br \/>\nremained enabled. Any programming style that has this sort of result is flawed<br \/>\nbeyond hope of redemption. Abandon that style. <\/p>\n<hr>\n<h3><a name=\"Manipulating Global Variables\">Manipulating Global Variables<\/a><\/h3>\n<p>Severity: <a href=\"#Poor style\">poor style<\/a>, <a href=\"#Deeply suspect\"><br \/>\ndeeply suspect<\/a>, <a href=\"#Serious\">serious<\/a><\/p>\n<p>There are very, very few global variables needed in a C++\/MFC program.<br \/>\nGenerally, these variables represent key global state which is the <i>raison<br \/>\nd&#8217;\u00c3\u00aatre<\/i> of the program. Other global variables, incidental to the actual<br \/>\ncomputations being performed, are usually a mistake.<\/p>\n<p>Perhaps the worst mistake committed is the use of global variables which are<br \/>\nused or manipulated by a dialog. This results in a dialog which cannot be reused<br \/>\neasily, and introduces possibilities of serious errors during maintenance.<\/p>\n<p>Now let&#8217;s get something established at the start here: I come from the school<br \/>\nof &quot;Global Variables Considered Harmful&quot;. I mean that literally. My<br \/>\nPh.D. dissertation advisor and one of my committee members wrote a paper of that<br \/>\ntitle:<\/p>\n<p><span class=\"h\"><b>W. Wulf and M. Shaw. <i>Global variables considered<br \/>\nharmful<\/i>. Sigplan Notices, 8(2):28&#8211;34, February 1973. 17.<\/b><\/span><\/p>\n<p><span class=\"h\">Since there is no reason to use global variables (except for<br \/>\nthe basic program state being manipulated), my rule is<br \/>\nthat no dialog I ever write will use a global or static variable, with the<br \/>\npossible exception of a table labeled as a <b>static const<\/b> table and<br \/>\ndeclared in the source module of the dialog.<\/span><\/p>\n<p><span class=\"h\">Note that many programmers show a proclivity to stuff all<br \/>\nsorts of variables into the <b>CWinApp<\/b>-derived class or the <b>CMainFrame<\/b><\/p>\n<p>class, and sprinkle constructs like<\/span><\/p>\n<pre><span class=\"h\">((CMyApp *)AfxGetApp())-&gt;somevariable<\/span><\/pre>\n<p><span class=\"h\">throughout the program. This is functionally identical to the<br \/>\nuse of global variables. Unfortunately, they rationalize this as &quot;I&#8217;m not<br \/>\nusing a global variable, I&#8217;m using a member variable of a class!&quot; This is<br \/>\narrant nonsense. The <i>real<\/i> issue is the encapsulation of information, and<br \/>\nstatements like the one above demonstrate a profound violation of the concept of<br \/>\nencapsulation. Having a document, a view, a dialog, or whatever sharing some<br \/>\nvariable in the <b>CWinApp<\/b>-derived class violates all sorts of principles of<br \/>\nencapsulation, and as such is no better than the use of a global variable.<\/span><\/p>\n<p><span class=\"h\">Dialogs which need to obtain values from, or communicate<br \/>\nvalues to, their parent can easily do so by using <b>SendMessage<\/b>. Read my<br \/>\nessay on <a href=\"messages.htm\">messaging<\/a> for more information. This in<br \/>\nparticular applies to modeless dialogs. A toolbox-style dialog, that is, one<br \/>\nthat is supposed to apply to the current view, I implement by having it <b>SendMessage<\/b><\/p>\n<p>to the mainframe:<\/span><\/p>\n<pre><b><span class=\"h\">AfxGetMainWnd()-&gt;SendMessage(...);<\/span><\/b><\/pre>\n<p><span class=\"h\">and have the mainframe do a <b>GetActiveView()<\/b> to forward<br \/>\nthe message.<\/span><\/p>\n<pre><i>in the message map\r\n<\/i><b>ON_REGISTERED_MESSAGE(UWM_SOME_VALUE_CHANGED, OnSomeValueValued)\r\n\r\n<\/b>...<i>the handler<\/i><span class=\"h\"><b>\r\nLRESULT CMainFrame::OnSomeValueChanged(WPARAM wParam, LPARAM lParam)\r\n   {\r\n     CView * view = GetActiveView();\r\n     if(view == NULL)\r\n       return 0; \/\/ or other appropriate value indicating failure\r\n     return view-&gt;SendMessage(UWM_SOME_VALUE_CHANGED, wParam, lParam);\r\n   }<\/b><\/span><\/pre>\n<p><span class=\"h\">Note that I can&#8217;t do this in the dialog because <b>GetActiveView<\/b><br \/>\nis a member of <b>CMainFrame<\/b>. This also makes the dialog easily reusable,<br \/>\nsince the only thing a client needs to know is that it sends a message to the<br \/>\nmainframe. Note my preference for Registered Window Messages, described in my<br \/>\nessay on <a href=\"messages.htm\">message management<\/a>.<\/span><\/p>\n<hr>\n<h3><span class=\"h\"><a name=\"Manipulating or calling members of another window class from within a window class\">Manipulating<br \/>\nor calling members of another window class from within a window class<\/a><\/span><\/h3>\n<p>Severity: <a href=\"#Poor style\">poor style<\/a>, <a href=\"#Serious\">serious<\/a><\/p>\n<p><span class=\"h\">This is a very common practice, and as far as I can tell, it<br \/>\nevolves from the C attitude that &quot;I can do anything I want to any data<br \/>\nstructure at any time I feel like it&quot;. This is an unhealthy attitude to<br \/>\nbring to OO programming. The key question is, why would you ever <i>need<\/i> to<br \/>\nmanipulate the member variables or call the member methods of sibling or parent window<br \/>\nclass? Hint: there are no right answers.&nbsp;The only time you want to<br \/>\nmanipulate variables in general (and there are people who are more fanatic than<br \/>\nI on this, who assert that this is even too much) is to set the public members<br \/>\nof a <b>CDialog<\/b> class before doing a <b>DoModal()<\/b> call. They argue, and<br \/>\nI philosophically agree with them, that these should <i>not<\/i> be public<br \/>\nvariables, but parameters to the constructor. And if they need to be queried,<br \/>\naccess functions should be provided to be called after <b>DoModal()<\/b> returns.<br \/>\nWe see exactly this approach in many MFC classes such as <b>CFileDialog<\/b>.<br \/>\nHowever, Microsoft&#8217;s ClassWizard is not especially programmer-friendly, and does<br \/>\nnot provide us the support we need to do this easily. It also makes sense to be<br \/>\nable to call the methods of child controls. But that&#8217;s as far as it makes sense<br \/>\nto go. Reaching into the <i>parent<\/i> is poor style. Manipulating variables in<br \/>\nthe <b>CWinApp<\/b> is inexcusable. Repeat after me: &quot;modularity is good.<br \/>\nmodularity is good. modularity is good!&quot;<\/span><\/p>\n<p><span class=\"h\">The inter-window communication mechanism is messages. In<br \/>\ngeneral, you shouldn&#8217;t even need a specifically-stored pointer to a window class<br \/>\nto send a message. A dialog would query state by doing a <b>GetParent()-&gt;SendMessage(&#8230;)<\/b><br \/>\nwhich is clean because the dialog then becomes entirely self-contained.<\/span><\/p>\n<p><span class=\"h\">In general, windows are independent entities and have no<br \/>\nbusiness knowing about each other in any detail, and certainly don&#8217;t need to<br \/>\nknow anything about the internal implementations of each other. Communication is<br \/>\nvia well-specified interfaces. For example, a dialog may mention a set of public<br \/>\nvariables which should be initialized before <b>DoModal<\/b> is called and a set<br \/>\nof public variables (perhaps the same set) from which values can be obtained<br \/>\nafter <b>DoModal<\/b> is completed. Other than that, nothing about the<br \/>\nimplementation needs to be known, <i>particularly<\/i> such nonsense as indexes<br \/>\ninto ListBoxes that don&#8217;t exist, which is what <b>UpdateData<\/b> does (see my<br \/>\nessays on &quot;<a href=\"updatedata.htm\">Avoiding UpdateData<\/a>&quot; and<\/p>\n<p>&quot;<a href=\"guiowner.htm\">Who Owns the GUI?<\/a>&quot;). Otherwise, if a<br \/>\ndialog needs to make a real-time query of its parent, it should use <b>SendMessage<\/b>,<br \/>\nand if it needs to set a value, it should use <b>SendMessage<\/b>.<\/span><\/p>\n<p><span class=\"h\">Views do not need to know about each other. In fact, it is<br \/>\ninconceivable to me that two views should know any details of each other, even<br \/>\nthat they exist. If you do something in a view, the only reason another view<br \/>\nneeds to know about it is because the first view has changed something. And<br \/>\nthat&#8217;s what a <b>CDocument<\/b>-derived class is for. If a view makes a change,<br \/>\nit notifies the document, and the document undertakes to notify any other views.<br \/>\nOr the view can simply ask the document to notify other views, using <b>UpdateAllViews<\/b>.<br \/>\nAll views (if any others) will be notified, but the view that is doing the<br \/>\nnotification doesn&#8217;t have to know that any other views even exist.<\/span><\/p>\n<p><span class=\"h\">One objection usually turns out to be something along the<br \/>\nlines of &quot;Well, I can write it syntactically, so why shouldn&#8217;t I be allowed<br \/>\nto do it?&quot; Sure, and you can program in assembly code, too, but that<br \/>\ndoesn&#8217;t mean that it makes sense. Good OO programming is a <i>discipline<\/i>.<\/span><\/p>\n<p><span class=\"h\">I elaborate a lot more on this set of problems in my<br \/>\ncompanion essay on the <a href=\"dlgctl.htm\">design of dialogs and controls<\/a>.<\/span><\/p>\n<hr>\n<h3><span class=\"h\"><a name=\"Manipulating the controls of a dialog\">Manipulating the controls of a dialog<\/a> from outside the dialog<\/span><\/h3>\n<p>Severity: (exceptionally) <a href=\"#Poor style\">poor style<\/a>,<br \/>\n<a href=\"#Serious\">serious<\/a><\/p>\n<p><span class=\"h\">I cannot imagine how this could ever make sense. A dialog is<br \/>\nan object, and the controls represent an internal implementation detail of the<br \/>\nclass. So nothing outside that class should know its implementation details. It<br \/>\nis true that the ClassWizard creates the control member variables as <b>public<\/b>,<br \/>\nbut I consider this a deep blunder representing an inadequate design of<br \/>\nClassWizard (it isn&#8217;t the worst or most egregious flaw in ClassWizard). I&#8217;ve<br \/>\nseen people trying to reach into modeless dialogs from outside it calling things<br \/>\nlike<\/span><\/p>\n<pre><span class=\"h\">(CEdit *)(modeless-&gt;GetDlgItem(IDC_NAME))-&gt;SetWindowText(s);<\/span><\/pre>\n<p><span class=\"h\">which is about as bad as you can get; second worst is<br \/>\nsomething like this, executed by a child dialog:<\/span><\/p>\n<pre><span class=\"h\">(CEdit *)(GetParent()-&gt;GetDlgItem(IDC_NAME))-&gt;GetWindowText(s);<\/span><\/pre>\n<p><span class=\"h\">These represent depths of tastelessness in OO programming<br \/>\nthat set my teeth on edge. For example, this style presumes that you know the<br \/>\nimplementation of the object being manipulated. So if you change the<br \/>\nimplementation for some reason, it means that places in your program you never<br \/>\nheard about now have to be changed, violating every known principle of good,<br \/>\nmodular design. For example, see my companion essay &quot;<a href=\"guiowner.htm\">Who<br \/>\nowns the GUI?<\/a>&quot;.<\/span><\/p>\n<p><span class=\"h\">For example, suppose I create a derived class based on a<br \/>\nstandard control, such as <b>CEdit<\/b> or <b>CListBox<\/b>. I then override<br \/>\nmethods of these controls. For example, my <a href=\"hscroll.htm\">ListBox class<\/a><\/p>\n<p>that automatically maintains its horizontal scrollbar is described in another<br \/>\nessay. I override <b>InsertString<\/b>, <b>AddString<\/b>, <b>ResetContents<\/b>,<br \/>\nand <b>DeleteString<\/b>. Now suppose you want to add something to this ListBox.<br \/>\nInstead of notifying the dialog to add something, so it correctly calls <b>CHListBox::InsertString<\/b>,<br \/>\nyou have done<\/span><\/p>\n<pre><span class=\"h\">((CListBox *)dlg-&gt;GetDlgItem(IDC_SOMELIST))-&gt;AddString(s);<\/span><\/pre>\n<p><span class=\"h\">which will call <b>CListBox::AddString<\/b>, <i>not<\/i> <b>CHListBox::AddString<\/b>.&nbsp;<\/span><\/p>\n<p><span class=\"h\">So, you say, suppose I do it &quot;right&quot; and access the<br \/>\ncorrect member variable, which is already bound to the correct type? Wouldn&#8217;t<br \/>\nthis solve the problem?<\/span><\/p>\n<pre><span class=\"h\">dlg-&gt;SomeList.AddString(s);<\/span><\/pre>\n<p><span class=\"h\">That solves one problem, but now it means that the dialog<br \/>\ncontents can be modified in ways that are not expected. Suppose I am using an<br \/>\nowner-draw ListBox, and I want to modify the structure that is used. Now I have<br \/>\nto locate all the places inside my program where that operation is performed,<br \/>\nand modify all of them as well! If I did it only in my dialog, I would have the<br \/>\ncontrol localized to exactly one place. This is why I frequently make such<br \/>\nstructures protected within the dialog.<\/span><\/p>\n<p><span class=\"h\">The <i>correct<\/i> specification of this is to have a method<br \/>\nwhich is invoked to perform the data setting or retrieval; it is up to that<br \/>\nmethod to decide, within the confines of the dialog, how to implement the<br \/>\nfunctionality that effects the desired change or retrieval. Nothing outside the<br \/>\ndialog needs to know how this is done. The cleanest method by far is to use <b>SendMessage<\/b><br \/>\nas the mechanism. So I would do something like<\/span><\/p>\n<pre><span class=\"h\">modeless-&gt;SendMessage(UWM_GET_NAME, buffer, size);<\/span><\/pre>\n<p><span class=\"h\">where I would write the specification<\/span><\/p>\n<pre><span class=\"h\">\/*******************************************************************\r\n*                            UWM_GET_NAME\r\n* Inputs:\r\n*        WPARAM: (WPARAM)(LPTSTR) pointer to a buffer to be filled\r\n*        LPARAM: (LPARAM)(DWORD)  the size of the buffer\r\n* Result: LRESULT\r\n*        Logically void, zero, always\r\n* Effect:\r\n*        Fills the buffer with the name supplied by the user\r\n*******************************************************************\/\r\n#define UWM_GET_NAME <i>see_my_<a href=\"messages.htm\">essay_on_messaging<\/a><\/i><\/span><\/pre>\n<p><span class=\"h\">This defines a clean modular interface between the dialog and<br \/>\nits clients.<\/span><\/p>\n<p><span class=\"h\">Think of messages being a clean way to invoke virtual<br \/>\nmethods, and you have the right idea.<\/span><\/p>\n<p><span class=\"h\">However, this leads to another of the horrors: simulating<br \/>\ncontrol messages from outside the dialog by sending messages to the dialog. This<br \/>\nis never sensible. For example, someone wants to get the effect of clicking the<br \/>\n&quot;Do Something&quot; button. They will code<\/span><\/p>\n<pre><span class=\"h\">dialog-&gt;SendMessage(WM_COMMAND, \r\n<\/span>                    (WPARAM)<span class=\"h\">MAKELONG(IDC_DO_SOMETHING, BN_CLICKED), \r\n                    (LPARAM)dialog-&gt;GetDlgItem(IDC_DO_SOMETHING));<\/span><\/pre>\n<p><span class=\"h\">(that is, assuming they can actually read the documentation;<br \/>\nmost do something far sillier:<\/span><\/p>\n<pre><span class=\"h\">dialog-&gt;SendMessage(BN_CLICKED, 0, 0)<\/span><\/pre>\n<p><span class=\"h\">or something equally bad). This pathetic attempt at<br \/>\nnotification is in the same class as manipulating the controls. It is just the<br \/>\nwrong approach. Note that the sender had to know the control ID of the control,<br \/>\nthe type of the control, etc. These are all violations of object integrity.<\/span><\/p>\n<p><span class=\"h\">The only correct solution is to use <b>SendMessage<\/b> to<br \/>\nsend a user-defined message to the dialog. Then the dialog decides how that<br \/>\nmessage is handled. It <i>might<\/i> call the same functions as the button-click<br \/>\nhandler; it might not. <i>It is none of your business, as the initiator, how<br \/>\nthis is implemented<\/i>.<\/span><\/p>\n<p><span class=\"h\">The correct, and for all practical purposes, the <i>only<\/i><br \/>\ncorrect, method of requesting a dialog, <b>CFormView<\/b>, or other such window<br \/>\nperform something is to send it a user-defined message. For example, <b>SendMessage<br \/>\n<\/b>or <b>PostMessage<\/b>. As an example,&nbsp;<\/span><\/p>\n<pre><span class=\"h\">dialog-&gt;SendMessage(UWM_SOME_USER_MESSAGE);<\/span><\/pre>\n<p><span class=\"h\">with the possible addition of a <b>WPARAM <\/b>or <b>LPARAM <\/b>value.<\/span><\/p>\n<p><span class=\"h\">One of the nicer features of VS7 (Visual Studio .NET 2002 and<br \/>\nVisual Studio .NET 2003) is that you can declare the variables <b>protected<\/b>.<br \/>\nYou should declare all member variables, especially control variables, and all<br \/>\nmessage handler functions, <b>protected<\/b>. The only <b>public<\/b> variables to<br \/>\na dialog are those you use to pass information into and out of the dialog; and<br \/>\nby &quot;pass into&quot; I mean &quot;those variables whose values must be set before creating<br \/>\nthe dialog&quot;, and by &quot;pass out of&quot; I mean &quot;those variables whose values contain<br \/>\ninformation to be retrieved after the dialog has terminated&quot;. They are <i>never<\/i> <\/p>\n<p>used to communicate information to anyone during the lifetime of the dialog, and<br \/>\nparticularly they are never accessed by any child dialogs.<\/span><\/p>\n<hr>\n<p><span class=\"h\"><font size=\"4\"><b><a name=\"Drawing on the dialog\">Drawing on<br \/>\nthe dialog<\/a><\/b><\/font><\/span><\/p>\n<p>Severity: insanely <a href=\"#Poor style\">poor style<\/a>, hard to get working<br \/>\n(if ever), easy to break<\/p>\n<p><span class=\"h\">Many people are tempted to draw things on the dialog, by<br \/>\noverriding the <b>OnPaint<\/b> handler in their <b>CDialog-<\/b>derived class.<br \/>\nAssume that for all practical purposes this is always a mistake. As far as I can<br \/>\ntell, the only construable excuse might be to use a bitmap image as the<br \/>\nbackground for the dialog, and even them I&#8217;m deeply suspect of this excuse.<\/span><\/p>\n<p><span class=\"h\">Don&#8217;t do it! Don&#8217;t even bother trying! Else you will end up<br \/>\nposting questions of the form &quot;I tried to draw &#8230; on my dialog, and it &#8230;.&lt;<i>description<br \/>\nof numerous unexpected results<\/i>&gt;&quot;. These usually include random<br \/>\ndisappearances, solid disappearances, flickering, ovewriting other controls, and<br \/>\na few other things I can&#8217;t recall at the moment. Not that it matters&#8211;the<br \/>\nproblems <i>go away<\/i> when you give up trying to write on the dialog.<\/span><\/p>\n<p><span class=\"h\">If you need to draw on a dialog, create a static control, and<br \/>\ndraw in that. This is always the simplest answer. For example, I once needed to<br \/>\ndraw arrows that went from box to box on a dialog. To do this, I simple created<br \/>\na <b>CArrow<\/b> subclass, and in its <b>OnPaint<\/b> handler I used 1 bit to<br \/>\nindicate its direction (N\/S, E\/W&#8211;all arrows are only horizontal or vertical),<br \/>\nand two bits to indicate which ends got arrowheads (00 &#8211; neither, 01 &#8211; N\/E, 10 &#8211;<br \/>\nS\/W, 11 &#8211; both ends). The 00 combination gave me &quot;thick lines&quot; so I could draw<br \/>\nL-shaped and other non-simple arrows. Not once did I draw anything on the<br \/>\nsurface of the dialog.<\/span><\/p>\n<p><span class=\"h\">I&#8217;ve never tried to draw on a dialog, and I&#8217;ve never had<br \/>\nproblems. Every week or two someone posts a question on the newsgroup that<br \/>\nstarts out with that &quot;I tried to draw &#8230; on my dialog&quot; and then describes some<br \/>\nbizarre behavior. Patient: &quot;Doctor, it hurts when I do this&quot; Doctor: &quot;Then don&#8217;t do that!&quot;. The<br \/>\neasiest way to solve a problem is to avoid choosing a way that is going to fail,<br \/>\nand use a way that is known to work, is easier to use, has no known problems,<br \/>\nand is utterly reliable.<\/span><\/p>\n<p><span class=\"h\">Even to do the background of a dialog, I simply put a static<br \/>\ncontrol with the <b>WS_CLIPSIBLINGS<\/b> style down, and put the background<br \/>\nbitmap in it. I&#8217;ve even done it using <b>OnPaint<\/b> and <b>StretchBlt<\/b> to<br \/>\nfill the dialog area, which works pretty well for most situations, but looks<br \/>\nreally bad if you have a resizable dialog that can get very much smaller or very<br \/>\nmuch larger than the background bitmap, but this is a defect in <b>StretchBlt<\/b><br \/>\nand doing your own painting on the dialog won&#8217;t make it go away.<\/span><\/p>\n<hr>\n<p><span class=\"h\"><font size=\"4\"><b><a name=\"Using GetDC\">Using GetDC<\/a><\/b><\/font><\/span><\/p>\n<p>There is rarely a need to use <b>GetDC<\/b>. The need is so rare and unusual<br \/>\nthat it is safe to assume that if you are writing <b>GetDC(&nbsp;)<\/b>, you have made<br \/>\na mistake. Part of the reason for this is that the number of times I see people<br \/>\nwrite <b>GetDC(&nbsp;) <\/b>without writing <b>ReleaseDC<\/b> is horrendous. <\/p>\n<p>Generally, you don&#8217;t need to get a DC at all. Certainly if you think you need<br \/>\nto get a DC for drawing, you should be immediately suspect. If you are doing<br \/>\n&quot;rubber-band&quot; objects (lines, selection rectangles, etc.) you need a DC other<br \/>\nthan in the <b>OnPaint<\/b> handler, and occasionally you may need to compute a<br \/>\ntext width, but the rest of the time, ask yourself, &quot;Do I<br \/>\nreally need a DC?&quot; If the answer is &quot;Yes, of course, to paint&quot; and you aren&#8217;t<br \/>\ndoing rubber-banding in an <b>OnMouseMove<\/b> handler, you have probably made a<br \/>\nfundamental error. If you are not computing some text width<br \/>\nsomewhere, the answer again is that you have probably made a fundamental error. <\/p>\n<p>Given that you need a DC, the correct way in MFC to do it is to use the<br \/>\n<b>CClientDC<\/b> data type, e.g. instead of writing<\/p>\n<pre>    CDC * dc = GetDC();\r\n    ... do something with DC\r\n    ReleaseDC(dc);<\/pre>\n<p>you should be writing<\/p>\n<pre>    CClientDC dc(this);\r\n    ...do something with DC<\/pre>\n<p>Note that no release is required because the destructor of the <b>CClientDC<\/b><br \/>\nhandles the release.<\/p>\n<hr>\n<h3><a name=\"Thinking you have one monitor\">Thinking you have one monitor<\/a><\/h3>\n<p>Severity: deeply suspect<\/p>\n<p>OK, I confess: I&#8217;ve done this far too much. Back in the Bad Old Days of<br \/>\nsingle monitors, you could tell where something was by simply looking at the<br \/>\ncoordinates of the window. If they were negative, you were off-screen somewhere.<br \/>\nIf any of them exceeded <b>::GetSystemMetrics(SM_CXSCREEN)<\/b> and\/or <b>::GetSystemMetrics(SM_CYSCREEN)<\/b><br \/>\nmeant you were offscreen in the other direction. I&#8217;ve even heard that people<br \/>\nwill &quot;move a window offscreen&quot; instead of using the more sensible <b>::ShowWindow(SW_HIDE)<\/b> <\/p>\n<p>by setting the coordinates to be large enough in some direction to force the<br \/>\nwindow offscreen. And the other thing I got wrong was fixing a different bug: if<br \/>\nyou store the window placement somewhere, such as in the Registry, and the<br \/>\nscreen resolution is changed (usually to a lower value), the window will end up<br \/>\noffscreen. This results in a window being unintentially invisible if its former<br \/>\ncoordinates were no longer on-screen given the new resolution, and often it was<br \/>\nnearly impossible to force the window back on-screen. So I&#8217;d compare the<br \/>\ncoordinates of the window to the coordinates of the screen, and if it was out of<br \/>\nrange, I&#8217;d force it onscreen.<\/p>\n<p>Alas, it ain&#8217;t so any longer. Multiple-monitor support has been with us for<br \/>\nseveral years, and it is now time to abandon the old ideas and move on with the<br \/>\nrest of the world.<\/p>\n<p>&nbsp;<\/p>\n<hr>\n<h3><span class=\"h\"><a name=\"Using #include\">Having an #include of the app file in every module<\/a><\/span><\/h3>\n<p><span class=\"h\">Severity: <a href=\"#Poor style\">poor style<\/a>, <a href=\"#Inefficient\">inefficient<\/a><br \/>\n(development)<\/span><\/p>\n<p><span class=\"h\">Unfortunately, the ClassWizard does this for you. I consider<br \/>\nthis one of the numerous serious defects in the ClassWizard. There are virtually<br \/>\nno modules in your program, except the <b>CWinApp<\/b>-derived module and the <b>CMainFrame<\/b>-derived<br \/>\nmodule, that need access to the application object (many components may invoke<br \/>\nmethods of the generic <b>CWinApp<\/b> class such as <b>LoadCursor<\/b> and such,<br \/>\nbut they do not need the <b>CWinApp<\/b>-derived header file included). The<br \/>\ninclusion of this file makes it impossible to reuse the class in any other app.<br \/>\nIn general, I try to immediately remove this <b>#include<\/b>. Mostly I can just<br \/>\nremove it. However, in many situations all I need to replace it with is<\/span><\/p>\n<pre><span class=\"h\">#include &quot;resource.h&quot;<\/span><\/pre>\n<p><span class=\"h\">which is all you usually need.<\/span><\/p>\n<p><span class=\"h\">Not only does the presence of this file tempt you to access<br \/>\nmember variables and methods of the <b>CWinApp<\/b> class, which is usually poor<br \/>\nstyle, but it also means that every time you happen to modify the <b>CWinApp<\/b><br \/>\nclass, every module that includes its header has to be recompiled, whether the<br \/>\nmodule needs the definitions or not, which is simply stupid. If you aren&#8217;t using<br \/>\nanything in the module, it should not have a dependency. This links to the<br \/>\nnotion of &quot;<a href=\"#Global Header Files\">global header files<\/a>&quot; which is equally sloppy.<\/span><\/p>\n<hr>\n<h3><span class=\"h\"><a name=\"Global Header Files\">Global (or &quot;umbrella&quot;) header<br \/>\nfiles<\/a><\/span><\/h3>\n<p>Severity: <i>unbelievably<\/i> <a href=\"#Poor style\">poor style<\/a><\/p>\n<p><span class=\"h\">There is an extremely unfortunate habit that many programmers<br \/>\ndevelop, which is to dump every possible definition of every possible variable<br \/>\ninto a single header file, with some name like &quot;<font face=\"Courier New\">global.h<\/font>&quot; or &quot;<font face=\"Courier New\">all.h<\/font>&quot;<br \/>\nor something like that. This technique has offended me for decades. I always<br \/>\nsaid this was a really stupid thing to do, because it means that every change<br \/>\nyou make recompiles nearly everything. I was generally told I was just flaming.<\/span><\/p>\n<p><span class=\"h\">Now I have proof. If you want to see it, get a copy of Ellen<br \/>\nBorison&#8217;s PhD dissertation,&nbsp;<\/span><\/p>\n<blockquote>\n<p><span style=\"font-size:10.0pt;font-family:&quot;Times New Roman&quot;;\nmso-fareast-font-family:&quot;Times New Roman&quot;;mso-bidi-font-family:&quot;Times New Roman&quot;;\nmso-ansi-language:EN-US;mso-fareast-language:EN-US;mso-bidi-language:AR-SA\"><b>\u00e2\u20ac\u0153Program<br \/>\nChanges and the Cost of Selective Recompilation\u00e2\u20ac\u009d, PhD Dissertation, Department<br \/>\nof Computer Science, Carnegie-Mellon University, May, 1989.<\/b><\/span><\/p>\n<\/blockquote>\n<p><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">In<br \/>\nthis she demonstrates beyond the shadow of any doubt that this technique is<br \/>\nalways a poor methodology.<\/span><\/p>\n<p><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">A<br \/>\nmodule should include <i>exactly<\/i> those header files it requires, and no<br \/>\nmore. There are two methods that can be adopted. One is to do all the <\/span><span style=\"mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\"><font face=\"Courier New\" size=\"2\">#include<\/font><\/span><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">s<br \/>\n&quot;flat&quot; style, that is, no header file includes any other header file.<br \/>\nA slightly cleaner method is that a header file which requires that some other<br \/>\nheader file be included do the <\/span><span style=\"mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\"><font face=\"Courier New\" size=\"2\">#include<\/font><\/span><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\"><\/p>\n<p>itself, and that all <\/span><span style=\"mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\"><font face=\"Courier New\" size=\"2\">#include<\/font><\/span><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\"><br \/>\nfiles have some sort of protection against multiple inclusion.<\/span><\/p>\n<p><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">In<br \/>\naddition, there is a tendency to say &quot;well, since I have included these six<br \/>\nfiles in every compilation unit, I really need to make a single #include that<br \/>\ncontains all six files&quot;. OK, maybe that makes sense. Just barely. But that<br \/>\nis the start of the &quot;slippery slope&quot; effect, wherein you then add a<br \/>\nseventh, and an eighth, and a twenty-second, and a thirty-fifth, and pretty soon<br \/>\nevery header file you have is defined in that header file and no matter what you<br \/>\ndo, everything recompiles. This is <i>lousy<\/i> programming style. It introduces<br \/>\ngratuitous interdependencies that do not exist. It also tempts you to using<br \/>\nsloppy programming style; since you have all those definitions, you just<br \/>\nconcatenate accesses to get such grotesquely ugly expressions as<\/span><\/p>\n<pre><span style=\"mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">BOOL changed = (CEdit *)((CMyApp *)AfxGetApp())-&gt;modeless-&gt;(GetDlgItem(IDC_NAME)))-&gt;GetModify();<\/span><\/pre>\n<p><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">Don&#8217;t<br \/>\nlaugh. I saw this in one program! It was memorable. Read my sections in this<br \/>\nessay on <a href=\"#Manipulating Global Variables\">avoiding global variables<\/a><br \/>\nand <a href=\"#Manipulating the controls of a dialog\">manipulating dialog<br \/>\ncontrols<\/a> to see why this incorporates some of the grossest programming I<br \/>\nhave ever encountered.&nbsp;<\/span><\/p>\n<p><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">If<br \/>\nyou need a global function (one whose behavior is defined entirely by its input<br \/>\nparameters, for example), just create a file to hold it, create a header file to<br \/>\ndefine it, and include that header file in the very few modules that use the<br \/>\nfunction. In the presence of modern browsing technology (such as the Class View<br \/>\nof VC++), there is <i>no<\/i> loss of ease of use, and you don&#8217;t end up with<br \/>\nmodules which have every sort of mishmash of functions in them. A good<br \/>\nprogrammer I knew years ago said &quot;You know you are in trouble if you write<br \/>\na file called &quot;<\/span><span style=\"mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\"><font face=\"Courier New\">util.c<\/font><\/span><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">&quot; that holds all your &quot;utility&quot;<\/p>\n<p>functions. You probably are clueless about program structure&quot;. I learned<br \/>\nfrom that, and have never since written such a file, independent of what name it<br \/>\nmight have. That was something like 25 years ago.<\/span><\/p>\n<hr>\n<h3><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\"><a name=\"Reaching across classes\">Reaching<br \/>\nacross classes<\/a><\/span><\/h3>\n<p>Severity: <a href=\"#Potentially fatal\">potentially fatal<\/a><\/p>\n<p><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">There<br \/>\nis a perennial set of blunders that start out with a question of the form<\/span><\/p>\n<p><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">&quot;I<br \/>\nwant to access the contents of my [document, view, dialog] from the mainframe. I<br \/>\nam doing &#8230; and it doesn&#8217;t work. What am I doing wrong?&quot;<\/span><\/p>\n<p><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">This<br \/>\nis usually accompanied by some grotesque code example such as<\/span><\/p>\n<pre><span style=\"font-size: normal; font-family: Courier New; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\"><font size=\"2\">CEdit * data = (CEdit *)(&amp;my_View-&gt;m_InputName)<\/font><\/span><\/pre>\n<p><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">or<br \/>\nsomething equally appalling. There is no excuse for writing such execrable code.<br \/>\nIf you have something that involves a view, put the code in the view. Use<br \/>\nmessages to transmit information if necessary. For example, I might write<\/span><\/p>\n<pre>CView * view = GetCurrentView();\r\nCString * name = NULL;\r\nif(view != NULL)\r\n    name = (CString *)view-&gt;SendMessage(UWM_QUERY_NAME);<\/pre>\n<p>although it is more likely I would not do anything in the mainframe that<br \/>\nrequired such precise information from a view. You should neither know nor care<br \/>\nabout the type of the view. A view which understands the message will respond to<br \/>\nit. One which does not will ignore it, and you will get <b>NULL<\/b> or 0 or <b><br \/>\nFALSE<\/b> back. <i>Maintain your abstractions!<\/i><\/p>\n<p><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">In<br \/>\na sane and responsible world, control variables would have been declared <b>protected<\/b>;<br \/>\nit is a design defect of the ClassWizard that makes them public. Similarly, a<br \/>\ndocument must never reach into a view, a view should never reach into a dialog<br \/>\n(except for setting input and retrieving output variables of a modal dialog),<br \/>\nand so on. Just because the language allows some horrible kludge is not a<br \/>\njustification for writing one.&nbsp;<\/span><\/p>\n<p><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">A<br \/>\nvariant of this is the one where the questioner says: &quot;I have this custom<br \/>\ncontrol and it needs to call a method\/access a variable of the parent class. I<br \/>\ndid the following&#8230;&quot; usually accompanied by some ghastly example of the<br \/>\nform<\/span><\/p>\n<pre><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">classs CSomething : public CStatic {\r\n     public:\r\n        CMyParent * parent;\r\n        ...\r\n    };<\/span><\/pre>\n<p><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">and<br \/>\nan access of the form<\/span><\/p>\n<pre><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">parent-&gt;SomeMethod();\r\nparent-&gt;SomeVariable = ...;\r\n... = parent-&gt;SomeVariable;<\/span><\/pre>\n<p><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">They<br \/>\nare often perplexed that the code does not compile. Usually some helpful soul on<br \/>\nthe newsgroup will point out that they need to <b>#include &quot;MyParent.h&quot;<\/b><\/p>\n<p>or some equally bad piece of advice.<\/span><\/p>\n<p><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">This<br \/>\nusually solves the problem about the program compiling. It does not solve the<br \/>\nmore fundamental problem, that the person writing the code is totally clueless<br \/>\nabout program structure.<\/span><\/p>\n<p><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">A<br \/>\ndialog or child control does not need to know anything about its parent. Ever.<br \/>\nIt has a set of clean interfaces that specify its behavior, <i>entirely in terms<br \/>\nof the control or dialog itself<\/i>. It is up to the outside world to meet the<br \/>\nconstraints of this interface specification.&nbsp;<\/span><\/p>\n<p><span style=\"font-family: Times New Roman; mso-fareast-font-family: Times New Roman; mso-bidi-font-family: Times New Roman; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA\">A<br \/>\ndialog or control that knows anything at all about its parent is a design so<br \/>\npoor that there is no salvaging it. See my essay on Dialog and Control Design.<\/span><\/p>\n<hr>\n<p><b><font size=\"4\"><a name=\"Overriding CWinThread::Run\">Overriding<br \/>\nCWinThread::Run<\/a> or CWinApp::Run<\/font><\/b><\/p>\n<p>Severity: Almost always <a href=\"#Poor style\">poor style<\/a>. <i>Abysmally<\/i> <\/p>\n<p>poor style<\/p>\n<p>Every time I have seen someone override <b>CWinThread::Run<\/b> (which is <b><br \/>\nCWinApp::Run<\/b>, because <b>CWinApp<\/b> is a subclass of <b>CWinThread<\/b>) it<br \/>\nhas represented something that could have been done more readily by another<br \/>\nmechanism. Simpler, faster, easier, and more reliable code would result. It is<br \/>\nalmost always the result of failing to understand how MFC works, and kludging in<br \/>\nsomething based upon having once read a book on pure Win32 programming.<\/p>\n<p>For example, people who create UI threads, that override <b>CWinThread::Run<\/b> <\/p>\n<p>and put an infinite loop inside, have missed the fact that they should have used<br \/>\na worker thread, and not a UI thread (a similar mistake is made if they put the<br \/>\ninfinite loop in their <b>InitInstance<\/b> handler and return <b>FALSE<\/b> when<br \/>\nit exits). There was no reason to use a UI thread!<\/p>\n<p>Another common failure is to create a thread, and override <b>CWinThread::Run<\/b><br \/>\nto have a <b>GetMessage<\/b> or <b>PeekMessage<\/b> loop. There is no point to<br \/>\nthis! That&#8217;s what the <b>Run<\/b> method already does! And it can be safely<br \/>\nassumed that the loop is probably wrong. For example, a <b>PeekMessage<\/b> loop<br \/>\nwhich has no blocking condition merely creates a mechanism for consuming 100% of<br \/>\nthe CPU.<\/p>\n<p>What is the proper solution?<\/p>\n<p>First, don&#8217;t use a UI thread if you meant to use a worker thread. This<br \/>\neliminates a number of failure modes. <\/p>\n<p>One excuse is &quot;I need to poll for incoming events, but do a loop that is<br \/>\ndoing something useful otherwise&quot;. There is already a better mechanism for doing<br \/>\nthis, the <b>OnIdle<\/b> handler. What you do in the <b>OnIdle<\/b> handler is<br \/>\npart of a computation; for example, in one application I got, each invocation of<br \/>\n<b>OnIdle<\/b> tested a flag to see if a report was being generated. If one was,<br \/>\nit generated <i>one line<\/i> of the report and returned <b>TRUE<\/b>. It kept<br \/>\nthis up until the report was completed (or cancelled). If the report completed<br \/>\nor was cancelled, the pending-report flag was cleared; if this flag was cleared,<br \/>\nit returned <b>FALSE<\/b>. This was a way to get &quot;background processing&quot; in a<br \/>\n16-bit Windows app. In Win32, this would actually be better handled by firing<br \/>\noff a thread to create the report.<\/p>\n<p>Another excuse is &quot;I need to process a message to cancel the loop&quot;, which is<br \/>\nsilly, because there is no need to process a message to cancel a loop. Read my<br \/>\nessay on <a href=\"workerthreads.htm\">worker threads<\/a>, including the section<br \/>\non thread cancellation.<\/p>\n<p>I&#8217;ve seen even weirder structures, so convoluted that even trying to explain<br \/>\nthem here would take more effort than I&#8217;m willing to expend. They were all<br \/>\nwrong. In many cases, the program simply never worked correctly, because the<br \/>\nwhole mechanism that was used was so deeply flawed that any illusion that it<br \/>\nworked was just that: an illusion. Under load conditions, the mechanism<br \/>\ncollapsed under its own weight.<\/p>\n<p>I&#8217;ve even seen someone put a <b>TranslateMessage\/DispatchMessage<\/b> handler<br \/>\nin the middle of a <b>CWinThread::Run<\/b>, for a thread <i>that had no windows!<\/i><br \/>\nAnd wondered why this was not handling thread messages (duh! Thread messages<br \/>\naren&#8217;t associated with windows! That&#8217;s why they&#8217;re called <i>thread<\/i> <\/p>\n<p>messages). Exactly how it was going to handle them escapes me.<\/p>\n<p>To handle thread messages, create a <b>WM_APP<\/b>-based message, or better<br \/>\nstill, a <b>RegisterWindowMessage<\/b> value, and use that in an <b><br \/>\nON_THREAD_MESSAGE<\/b> or <b>ON_REGISTERED_THREAD_MESSAGE<\/b> entry in the<br \/>\nMessage Map. See my essay on <a href=\"messages.htm\">Message Management<\/a> for<br \/>\nmore details on this, as well as my essay on <a href=\"uithreads.htm\">UI threads<\/a>.<\/p>\n<p>As far as I can tell, there is no need to ever override <b>CWinThread::Run<\/b>.<br \/>\nAssume, the instant you decide to do this, that you are wrong. That assessment<br \/>\nis correct so often that the times that overriding <b>CWinThread::Run<\/b> would<br \/>\nbe correct are measured in events-per-decade. Except that in nearly a decade of<br \/>\nMFC programming, I have yet to find a reason to ever override <b>CWinThread::Run<\/b>.<br \/>\nAnd I&#8217;ve done some pretty sophisticated UI threads.<\/p>\n<h1><span class=\"h\">Summary<\/span><\/h1>\n<p><span class=\"h\">I&#8217;m sure that I&#8217;ve manage to offend nearly everyone who has<br \/>\nread this with some opinion or the other, because I&#8217;ve slammed your favorite way<br \/>\nof doing things. That&#8217;s fine. I want you to <i>think<\/i> about what you are<br \/>\ndoing. Programs have the unfortunate characteristic that just because you <i>can<\/i><\/p>\n<p>do something in a certain way, you have not proven that is the <i>most effective<\/i><br \/>\nway to do things. Often programmers invent idioms which they use over and over<br \/>\nbecause they once carefully figured out how to reach inside abstractions and<br \/>\nextract what they need; this does not make that programming methodology clean or<br \/>\neffective. Just because &quot;it works&quot; does not make it<br \/>\n&quot;good&quot;.&nbsp;<\/span><\/p>\n<p><span class=\"h\">I work in a world in which I not only write code, but I have<br \/>\nto maintain it a year or two after I wrote it. I cannot build<br \/>\n&quot;fragile&quot; programs that might break. They are often maintained<br \/>\n(perhaps usually maintained) by unskilled labor, which includes myself a year or<br \/>\ntwo later. I cannot afford to do things that make simple changes complex.<\/span><\/p>\n<p><span class=\"h\">I use multithreading a lot. I have to be exceedingly careful<br \/>\nto get it right; any technique that is error prone is eventually fatal. I may<br \/>\nnot see conditions arise during testing that arise in normal use, and there can<br \/>\nbe thousands of copies of my program out there being used. Anything that is<br \/>\ndeadlock-possible <i>will <\/i><\/span>deadlock, and this reflects badly on my<br \/>\nclients&#8217; products, and in turn reflects badly on me. I am in the habit of<br \/>\ndelivering robust applications that I can tackle modifications on after having<br \/>\nseen tens of thousands of lines of other code for months. Adopting fairly rigid<br \/>\nstyles which are, if not impervious to changes under maintenance, are extremely<br \/>\ninsensitive to changes under maintenance, is critical (I prefer impervious when<br \/>\nI can achieve it).<\/p>\n<p>So this essay not only captures techniques which I use in my ordinary<br \/>\nprogramming, but also captures a set of bugs, stylistic errors, and fragilities<br \/>\nI encounter in nearly every program I am given to maintain. It is very sad, but<br \/>\nmost programs I get are fairly poorly written (probably because the well-written<br \/>\nones don&#8217;t need the kind of repairs I can give, sort of like healthy people not<br \/>\nneeding to see physicians as often as those with medical problems&#8211;I remember a<br \/>\npre-Monty-Python radio program [&quot;I&#8217;m Sorry, I&#8217;ll Read That Again&quot;] in<br \/>\nwhich John Cleese said something along the lines of &quot;I&#8217;m tired of being<br \/>\nforced to look into people&#8217;s filthy mouths! I&#8217;d like to fix something nice and<br \/>\nclean, like a broken arm, someday&quot; and the reply &quot;But you&#8217;re a <i>dentist<\/i>&quot;.<br \/>\nSo I sometimes have that feeling, too). So I&#8217;ve learned to look for these<br \/>\nproblems when I get symptoms that they would cause, and I find them. And I fix<br \/>\nthem.&nbsp;<\/p>\n<p>But it is a whole lot easier to not commit these crimes against good<br \/>\nprogramming in the first place.<\/p>\n<p><b><font size=\"1\">The views expressed in these essays are those of the<br \/>\nauthor, and in no way represent, nor are they endorsed by, Microsoft.<\/font><\/b> <\/p>\n<h5>Send mail to <a href=\"mailto:newcomer@flounder.com\">newcomer@flounder.com<\/a><br \/>\n with questions or comments about this web site.<br \/>\nCopyright \u00c2\u00a9 2002-2003 FlounderCraft Ltd.<br \/>\nAll Rights Reserved<br \/>\nLast modified: <\/p>\n","protected":false},"excerpt":{"rendered":"<p>This is an ugly dump of the html from this nice writeup&#8230; I just didn&#8217;t want to lose it&#8230; OK, so it&#8217;s a pun on &quot;The 7 Habits of Highly Effective People&quot;. But there are a number of programming techniques that I&#8217;ve found virtually instantly identify a defective program. In addition, there are a number [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"open","ping_status":"closed","template":"","meta":{"jetpack_post_was_ever_published":false,"footnotes":""},"class_list":["post-143","page","type-page","status-publish","hentry"],"aioseo_notices":[],"jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/P9M11L-2j","jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/bitpost.com\/news\/wp-json\/wp\/v2\/pages\/143","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bitpost.com\/news\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/bitpost.com\/news\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/bitpost.com\/news\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/bitpost.com\/news\/wp-json\/wp\/v2\/comments?post=143"}],"version-history":[{"count":0,"href":"https:\/\/bitpost.com\/news\/wp-json\/wp\/v2\/pages\/143\/revisions"}],"wp:attachment":[{"href":"https:\/\/bitpost.com\/news\/wp-json\/wp\/v2\/media?parent=143"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}