Tuesday, November 15, 2011

Synchronization Primitives Available in Win32

I ran into this table in a concurrency training class.  It gives you the quick and dirty on synchronization primitives available in Win32.

Characteristic
CriticalSection
SRWLocks
Mutex
Semaphores
Events
Kernel call even if free and upon creation
N
N
Y
Non-FIFO (no convoys)
Y
Y
N
Spin before wait option
Y
Y
N
Try to acquire option
Y
N/Y on Win7
N
Cross-process
N
N
Y
Recursive acquires
Y
N
Mutex only
Use in WaitForMultiple..
N
N
Y


  • CriticalSections are the lightest weight and normally the best to use.
    • you can use them recursively on the same thread
  • SRWLocks are best if you need to differentiate reading and writing access.  For example you can take a shared lock for read only access to a shared resource and exclusive lock for writing.
    • It is generally better than just using a critical section if the ratio is 2 reads : 1 write
    • Cannot be used recursively
  • Mutex/Semaphores/Events are kernel objects
    • Can be used across process.
    • Obviously available in krenel mode.
    • In user mode, the will be less performant than critical sections and SRWlocks and will cause more context switching.
    • Are processed in convoys so they can avoid starvation
Instrumentation is the best way to know what kind of synchronization is best for your code.  Look at my previous post on how to instrument with ETW and XPerf for industrial grade perf testing.  Try different synchronization mechanisms and measure performance.

Thursday, August 4, 2011

How to Add Instrumentation to Your Manifest

To enable ETW performance tracing for your binary, the first thing you need to do is add an instrumentation section. Here is the MSDN documentation on how to do this if you want to read about this in detail:

http://msdn.microsoft.com/en-us/library/aa382776(v=VS.85).aspx

Also in the introduction for ETW (http://msdn.microsoft.com/en-us/magazine/cc163437.aspx), they make a tool recommendation for generating a manifest for ETW (ecmangen.exe). It is available in the Windows SDK. You can try it out; it may meet your needs just fine. As a person who still favors writing code in Vi, I opted to roll my own. Tools are great when they work for you. Using a tool; however, doesn’t make up for actually knowing how things work. It is good to understand how things work when things don’t come together. Read on if you would rather roll your own.

So below is the events section instrumentation manifest that has one start and stop even. You will need a start and stop for everything you want to time.

<events>

<event

channel="50"

keywords="Component query"

level="win:Informational"

message="$(string.event_5501)"

opcode="win:Start"

symbol="CREATE_QUERY_START"

task="component_CreateQuery"

template="INFO_CONTEXT_INFO"

value="5500"

/>

<event

channel="50"

keywords="Component query"

level="win:Informational"

message="$(string.event_5502)"

opcode="win:Stop"

symbol="CREATE_QUERY_STOP"

task="component_CreateQuery"

template="INFO_CONTEXT_INFO"

value="5501"

/>

events>

With some highlighting, I will show you where all the bits line up inside the full manifest.

<events>

<event

channel="50"

keywords="Component query"

level="win:Informational"

message="$(string.event_5501)"

opcode="win:Start"

symbol="CREATE_QUERY_START"

task="component_CreateQuery"

template="INFO_CONTEXT_INFO"

value="5500"

/>

<event

channel="50"

keywords="Component query"

level="win:Informational"

message="$(string.event_5502)"

opcode="win:Stop"

symbol="CREATE_QUERY_STOP"

task="component_CreateQuery"

template="INFO_CONTEXT_INFO"

value="5501"

/>

events>

Here is the full manifest:

xml version='1.0' encoding='utf-8' standalone='yes'?>

<assembly

xmlns="urn:schemas-microsoft-com:asm.v3"

xmlns:xsd="http://www.w3.org/2001/XMLSchema"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

manifestVersion="1.0"

>

<assemblyIdentity

buildType="$(build.buildType)"

language="neutral"

name="Microsoft-Windows-Component"

processorArchitecture="$(build.arch)"

publicKeyToken="$(Build.WindowsPublicKeyToken)"

version="$(build.version)"

versionScope="nonSxS"

/>

<instrumentation xmlns:win="http://manifests.microsoft.com/win/2004/08/windows/events">

<events xmlns="http://schemas.microsoft.com/win/2004/08/events">

<provider

guid="{56c71c31-cfbd-4cdd-8559-505e042bbbe1}"

message="$(string.EventProviderName)"

messageFileName="%SystemRoot%\system32\component.dll"

name="Microsoft-Windows-ComponentProvider"

resourceFileName="%SystemRoot%\system32\component.dll"

symbol="component"

>

<channels>

<channel

chid="50"

name="Microsoft-Windows-ComponentProvider/Performance"

symbol="MS_COMPONENT_PERFORMANCE"

type="Analytic"

/>

channels>

<keywords>

<keyword

mask="0x1"

name="PerfTrackContext"

/>

<keyword

mask="0x2"

name="Component"

/>

<keyword

mask="0x4"

name="query"

/>

keywords>

<tasks>

<task

name="component_CreateQuery"

value="5000"

/>

tasks>

<templates>

<template tid="INFO_CONTEXT_INFO">

<data

inType="win:Pointer"

name="Context"

/>

template>

templates>

<events>

<event

channel="50"

keywords="Component query"

level="win:Informational"

message="$(string.event_5501)"

opcode="win:Start"

symbol="CREATE_QUERY_START"

task="component_CreateQuery"

template="INFO_CONTEXT_INFO"

value="5500"

/>

<event

channel="50"

keywords="Component query"

level="win:Informational"

message="$(string.event_5502)"

opcode="win:Stop"

symbol="CREATE_QUERY_STOP"

task="component_CreateQuery"

template="INFO_CONTEXT_INFO"

value="5501"

/>

events>

provider>

events>

instrumentation>

<localization>

<resources culture="en-US">

<stringTable>

<string

id="EventProviderName"

value="Microsoft-Windows-Component"

/>

<string

id="event_5501"

value="create query has started."

/>

<string

id="event_5502"

value="create query has exited."

/>

stringTable>

resources>

localization>

<dependency

discoverable="false"

optional="false"

resourceType="Resources"

>

<dependentAssembly dependencyType="prerequisite">

<assemblyIdentity

buildType="$(build.buildType)"

language="*"

name="Microsoft-Windows-Component.Resources"

processorArchitecture="$(build.processorArchitecture)"

publicKeyToken="$(Build.WindowsPublicKeyToken)"

version="$(build.version)"

versionScope="nonSxS"

/>

dependentAssembly>

dependency>

assembly>

Monday, July 18, 2011

Performance Instrumentation Testing for Windows Programming

Performance is something you should always build in as you are writing code whether you are building something from the ground up or working on bug fixes for some legacy code. Performance is one of those core software principals that is just good hygiene. Similarly you should always write secure code, reliable code, et cetera, but those are separate topics.

Performance considerations start at the very beginning when you start designing your features, and continue throughout the process. So, let’s say that you already came up with a high performance design that you validated through prototyping. Great, you are starting off the project on the right foot; as you know it becomes much harder to make design changes as the project goes down the pike, or even impossible towards the end of the development cycle.

So now you are in the thick of coding, or perhaps on the tail end of development, and you want to make sure that you are still meeting your performance goals for your feature work. Saying you are a good programmer and you always right high performance code isn’t quite good enough; you have to actually test your code. Writing code with timers in it and doing a printf with times is ok for prototypes, but doesn’t work for real production code. Not to worry, there are a number of tools at the Windows developer’s disposal to actually do the job right.

Profiling is one tool in the toolbox; one such profiler is Microsoft’s F1 made by the developer division. I think it is available in the wild as a standalone, or it looks like it has been included with VS08 and VS10. I personally have used the standalone F1 and still write code in Vim, but maybe I am weird like that. The basic idea of F1 is that it breaks into your process at a certain time interval and check to see what is on your threads’ call stacks. Based on what is on the stacks, F1 can give you ideas as to how much time is spent in each function, and about allocations being made. The advantages to using a profiler like F1 are: you don’t have to modify your binaries to instrument, it is light weight, and it gives you an idea how much time your code spends in functions. Some downsides are: you don’t get call count information, CPU usage is skewed by timer caused context switching, doesn’t profile kernel mode usage, it is less effective for system wide issues, it is heavy weight, and it doesn’t scale well if you want to profile often. To sum it up, F1 is a great tool with limitations. It really can give you a real-world performance view of your code (if it runs in UM), but there are better ways to instrument if want to look at performance more than a few times.

One of these better ways is ETW (Event Tracing for Windows). I will not get into the nitty-gritty of ETW; I will assume that the reader knows how to Google and can read the copious content out there, but I will give you a quick a dirty idea as to what it is. Basically ETW is the Windows operating system’s built in tracing mechanism. It is baked in all the way to the kernel level, and is very high performance. Since ETW is baked into the operating system, you can track scenarios from process to process to even KM components with very little overhead. You can use it for many other things as well, like writing events to logs and so on, but I will focus on using ETW for instrumenting your code for performance. For some reason though, I haven’t found too much help on the Internet on how to do performance instrumentation. I plan to help with that.

In the days and weeks to come, I will break it down how to instrument your code with ETW, and use the Windows tools for performance tracking and testing.

ETW Overview: http://msdn.microsoft.com/en-us/magazine/cc163437.aspx

Do not confuse ETW with WPP. Yes WPP is built on ETW, but I use WPP for more conventional printf style tracing. It is good to also add WPP tracing to your code for debugging purposes, but I don’t use it for performance testing. In fact WPP tracing is probably the best way to debug nasty concurrency issues that don’t repro well on a debugger, so you should look into it.

Friday, January 7, 2011

CreateThread Usage Pattern

I don’t really use the old thread pool (Windows 2000 & XP) in favor of the new awesome thread pool introduced in Vista, but sometimes you might inherit old code that does. I just finished fixing a bug related to the old CreateThread. I have some time before my team’s Friday afternoon party, so I thought I would share. I found the error thanks to App Verifier; +1 to App Verifier’s awesomeness.

Basically the usage pattern is:
1. get the module handle (GetModuleHandleEx)
2. create the thread (CreateThread)
3. If COM, CoInitialize a new apartment for the thread
4. Do work
5. If COM, CoUninitialize
6. FreeLibraryAndExitThread with the handle gotten in #1
7. Return

Steps 1-2, The thread creator would do something like this:

if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)&Class::ThreadProc , &s_hModule))
hr = HRESULT_FROM_WIN32( GetLastError() );

if (S_OK == hr) {
if (s_hThread)
CloseHandle(s_hThread);
s_hThread = CreateThread(NULL, 0, ThreadProc, this, 0, &s_dwThreadID);
if (!s_hThread) {
hr = HRESULT_FROM_WIN32(::GetLastError());
FreeLibrary( s_hModule );
}
}


In my case, the bug was in the GetModuleHandleEx. Take heed that if you are using the GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRES flag, then the second parameter should an address inside of your DLL; I have read that &__ImageBase or the HINSTANCE passed into DllMain should also do the trick. Also the third parameter will be used inside the thread proc.

Steps 3-7:

DWORD WINAPI Class::ThreadProc(void *pv)
{
if (S_OK == CoInitializeEx( NULL, COINIT_MULTITHREADED)) {
//...
// do work here
CoUninitialize();
}

FreeLibraryAndExitThread(s_hModule, 0);
return 0;
}


As always, read the documentation to go deeper in the topic.

Setting a Processor Breakpoint in WinDbg

If you have a variable like a pointer or a ref count that seems to be getting clobbered or incorrectly accessed, the ba (break on access) command can be a life saver. Setting a break on the memory address allows you to break in with windbg, inspect the stack, or do whatever else you need to do the moment the memory is accessed.

The basic usage is:
ba address access memory_size

Ex. Tracking write access of a pointer on an AMD64 machine:
ba 0000000070540018 w8

Ex. Tracking read/write of a DWORD ref count on x86:
ba 7124220 r4

Look at the windbg documentation for info.