Deadlock using CoCreateInstance and AfxLoadLibrary

Hello,

I have a simple test app that starts 5-10 threads and each thread
executes the below function.  I consistently see deadlocks when one
thread is calling CoCreate call while another thread calls
AfxLoadLibrary:

void CTest_app_tx4ole::OnAction2()
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	CLSID clsId;
	CLSIDFromProgID((CComBSTR)"anyprogid", &clsId);
	CString sThread;
	sThread.Format("%d", GetCurrentThreadId());
	for(int i(0); i<10000; ++i)
	{
		OutputDebugString((CString)"0 " + sThread + "\n");
		HMODULE hLib = AfxLoadLibrary("c:\\program files\\any.dll");

		OutputDebugString((CString)"1 " + sThread + "\n");
		CComPtr<IUnknown> spPtr;  // CoInit/CoUninit is called for each
thread

		OutputDebugString((CString)"2 " + sThread + "\n");
		spPtr.CoCreateInstance(clsId);

		OutputDebugString((CString)"3 " + sThread + "\n");
		AfxFreeLibrary(hLib);

		OutputDebugString((CString)"4 " + sThread + "\n");
	}
}

Windbg shows these locks, I would like to understand what has gone
wrong here!


0:013> !locks

CritSec ntdll!LdrpLoaderLock+0 at 77ce5340
WaiterWoken        No
LockCount          2
RecursionCount     2
OwningThread       13fc
EntryCount         0
ContentionCount    b
*** Locked

CritSec MFC42!_afxResourceLock+0 at 696d06f0
WaiterWoken        No
LockCount          9
RecursionCount     1
OwningThread       1c8
EntryCount         0
ContentionCount    a
*** Locked

Scanned 1349 critical sections



Thread 13fc:
ntdll!KiFastSystemCallRet
ntdll!NtWaitForSingleObject+0xc
ntdll!RtlpWaitOnCriticalSection+0x154
ntdll!RtlEnterCriticalSection+0x152
MFC42!AfxLockGlobals+0x73
MFC42!CDynLinkLibrary::CDynLinkLibrary+0x8f
MFC42!AfxCoreInitModule+0x4d
PVFormsData!DllMain+0x1c
PVFormsData!_DllMainCRTStartup+0x50
ntdll!LdrpCallInitRoutine+0x14
ntdll!LdrpRunInitializeRoutines+0x36d
ntdll!LdrpLoadDll+0x437
ntdll!LdrLoadDll+0x1ad
kernel32!LoadLibraryExW+0x253
ole32!CClassCache::CDllPathEntry::LoadDll+0xae
ole32!CClassCache::CDllPathEntry::Create_rl+0x37
ole32!CClassCache::CClassEntry::CreateDllClassEntry_rl+0xd4
ole32!CClassCache::GetClassObjectActivator+0x224
ole32!CClassCache::GetClassObject+0x30
ole32!CServerContextActivator::CreateInstance+0x110
ole32!ActivationPropertiesIn::DelegateCreateInstance+0x108
ole32!CApartmentActivator::CreateInstance+0x112
ole32!CProcessActivator::CCICallback+0x6d
ole32!CProcessActivator::AttemptActivation+0x2c
ole32!CProcessActivator::ActivateByContext+0x4f
ole32!CProcessActivator::CreateInstance+0x49
ole32!ActivationPropertiesIn::DelegateCreateInstance+0x108
ole32!CClientContextActivator::CreateInstance+0xb0
ole32!ActivationPropertiesIn::DelegateCreateInstance+0x108
ole32!ICoCreateInstanceEx+0x403
ole32!CComActivator::DoCreateInstance+0xd9
ole32!CoCreateInstanceEx+0x38
ole32!CoCreateInstance+0x37
test_app_tx4ole!ATL::CComPtr<IUnknown>::CoCreateInstance+0x22
test_app_tx4ole!
CTest_app_tx4oleDlg::OnAction2+0x2e5                        // Calls
CoCreate
test_app_tx4ole!CTest_app_tx4oleDlg::DoBackgroundThread+0x13
msvcrt!_endthread+0x52
msvcrt!_endthread+0xdc
kernel32!BaseThreadInitThunk+0xe
ntdll!_RtlUserThreadStart+0x23


Thread 1c8:
ntdll!KiFastSystemCallRet
ntdll!NtWaitForSingleObject+0xc
ntdll!RtlpWaitOnCriticalSection+0x154
ntdll!RtlEnterCriticalSection+0x152
ntdll!LdrLockLoaderLock+0xe1
ntdll!LdrLoadDll+0xdd
kernel32!LoadLibraryExW+0x253
kernel32!LoadLibraryExA+0x1f
kernel32!LoadLibraryA+0xb7
MFC42!AfxLoadLibrary+0x17
test_app_tx4ole!
CTest_app_tx4oleDlg::OnAction2+0x16a                         // Calls
AfxLoadLibrary
test_app_tx4ole!CTest_app_tx4oleDlg::DoBackgroundThread+0x13
msvcrt!_endthread+0x52
msvcrt!_endthread+0xdc
kernel32!BaseThreadInitThunk+0xe
ntdll!_RtlUserThreadStart+0x23

Thanks,
Jay
0
9/15/2008 4:40:35 PM
vc.mfc 33608 articles. 0 followers. Follow

1 Replies
1532 Views

Similar Articles

[PageSpeed] 15

Generally, you cannot call CoCreateInstance from DllMain, or from any function that is
invoked by DllMain.  Looking at your backtrace, that is what you are doing.  You also
cannot call anything that creates a thread from DllMain.  Read about the limitations on
DllMain in the MSDN.  It appears you are loading the DLL while holding the loader lock,
and this is caused by taking an action that loads a DLL (albeit indirectly) while the
loader lock is being held by another DLL activation.

This can also be implicit in static constructors used in a DLL.  
				joe
On Mon, 15 Sep 2008 09:40:35 -0700 (PDT), Jay Hamilton <jayhamiltoniv@gmail.com> wrote:

>Hello,
>
>I have a simple test app that starts 5-10 threads and each thread
>executes the below function.  I consistently see deadlocks when one
>thread is calling CoCreate call while another thread calls
>AfxLoadLibrary:
>
>void CTest_app_tx4ole::OnAction2()
>{
>	AFX_MANAGE_STATE(AfxGetStaticModuleState())
>
>	CLSID clsId;
>	CLSIDFromProgID((CComBSTR)"anyprogid", &clsId);
>	CString sThread;
>	sThread.Format("%d", GetCurrentThreadId());
>	for(int i(0); i<10000; ++i)
>	{
>		OutputDebugString((CString)"0 " + sThread + "\n");
>		HMODULE hLib = AfxLoadLibrary("c:\\program files\\any.dll");
>
>		OutputDebugString((CString)"1 " + sThread + "\n");
>		CComPtr<IUnknown> spPtr;  // CoInit/CoUninit is called for each
>thread
>
>		OutputDebugString((CString)"2 " + sThread + "\n");
>		spPtr.CoCreateInstance(clsId);
>
>		OutputDebugString((CString)"3 " + sThread + "\n");
>		AfxFreeLibrary(hLib);
>
>		OutputDebugString((CString)"4 " + sThread + "\n");
>	}
>}
>
>Windbg shows these locks, I would like to understand what has gone
>wrong here!
>
>
>0:013> !locks
>
>CritSec ntdll!LdrpLoaderLock+0 at 77ce5340
>WaiterWoken        No
>LockCount          2
>RecursionCount     2
>OwningThread       13fc
>EntryCount         0
>ContentionCount    b
>*** Locked
>
>CritSec MFC42!_afxResourceLock+0 at 696d06f0
>WaiterWoken        No
>LockCount          9
>RecursionCount     1
>OwningThread       1c8
>EntryCount         0
>ContentionCount    a
>*** Locked
>
>Scanned 1349 critical sections
>
>
>
>Thread 13fc:
>ntdll!KiFastSystemCallRet
>ntdll!NtWaitForSingleObject+0xc
>ntdll!RtlpWaitOnCriticalSection+0x154
>ntdll!RtlEnterCriticalSection+0x152
>MFC42!AfxLockGlobals+0x73
>MFC42!CDynLinkLibrary::CDynLinkLibrary+0x8f
>MFC42!AfxCoreInitModule+0x4d  
>PVFormsData!DllMain+0x1c        <===== You have called DllMain
>PVFormsData!_DllMainCRTStartup+0x50
>ntdll!LdrpCallInitRoutine+0x14
>ntdll!LdrpRunInitializeRoutines+0x36d
>ntdll!LdrpLoadDll+0x437
>ntdll!LdrLoadDll+0x1ad
>kernel32!LoadLibraryExW+0x253
>ole32!CClassCache::CDllPathEntry::LoadDll+0xae
>ole32!CClassCache::CDllPathEntry::Create_rl+0x37
>ole32!CClassCache::CClassEntry::CreateDllClassEntry_rl+0xd4
>ole32!CClassCache::GetClassObjectActivator+0x224
>ole32!CClassCache::GetClassObject+0x30
>ole32!CServerContextActivator::CreateInstance+0x110
>ole32!ActivationPropertiesIn::DelegateCreateInstance+0x108
>ole32!CApartmentActivator::CreateInstance+0x112
>ole32!CProcessActivator::CCICallback+0x6d
>ole32!CProcessActivator::AttemptActivation+0x2c
>ole32!CProcessActivator::ActivateByContext+0x4f
>ole32!CProcessActivator::CreateInstance+0x49
>ole32!ActivationPropertiesIn::DelegateCreateInstance+0x108
>ole32!CClientContextActivator::CreateInstance+0xb0
>ole32!ActivationPropertiesIn::DelegateCreateInstance+0x108
>ole32!ICoCreateInstanceEx+0x403
>ole32!CComActivator::DoCreateInstance+0xd9
>ole32!CoCreateInstanceEx+0x38
>ole32!CoCreateInstance+0x37
>test_app_tx4ole!ATL::CComPtr<IUnknown>::CoCreateInstance+0x22
>test_app_tx4ole!
>CTest_app_tx4oleDlg::OnAction2+0x2e5                        // Calls
>CoCreate
>test_app_tx4ole!CTest_app_tx4oleDlg::DoBackgroundThread+0x13
>msvcrt!_endthread+0x52
>msvcrt!_endthread+0xdc
>kernel32!BaseThreadInitThunk+0xe
>ntdll!_RtlUserThreadStart+0x23
>
>
>Thread 1c8:
>ntdll!KiFastSystemCallRet
>ntdll!NtWaitForSingleObject+0xc
>ntdll!RtlpWaitOnCriticalSection+0x154
>ntdll!RtlEnterCriticalSection+0x152
>ntdll!LdrLockLoaderLock+0xe1
>ntdll!LdrLoadDll+0xdd
>kernel32!LoadLibraryExW+0x253
>kernel32!LoadLibraryExA+0x1f
>kernel32!LoadLibraryA+0xb7
>MFC42!AfxLoadLibrary+0x17
>test_app_tx4ole!
>CTest_app_tx4oleDlg::OnAction2+0x16a                         // Calls
>AfxLoadLibrary
>test_app_tx4ole!CTest_app_tx4oleDlg::DoBackgroundThread+0x13
>msvcrt!_endthread+0x52
>msvcrt!_endthread+0xdc
>kernel32!BaseThreadInitThunk+0xe
>ntdll!_RtlUserThreadStart+0x23
>
>Thanks,
>Jay
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15973)
9/17/2008 1:53:03 PM
Reply:

Similar Artilces:

Refer to sheets without using tab name??
Cell formulas that refer to other sheets usually look like this: =Sheet2!A1 ' Get cell A1 from Sheet2 However, what if someone changed the name of the Sheet2 tab to something like "ThisIsMyTab"??? Does that mean I would have to manually change all possible formulas to the following: =ThisIsMyTab!A1 ????? I'm mostly curious if there's a way to use formulas that do not strictly rely on the names of always changing tab sheet names. thank you Hello, The best way is to test it by yourself. I...

Using Repair Permissions
Using Repair Permissions comes up quite often on this list. I ran across this on Apple Discussions today and thought I would pass this along. You do not need to Repair Permissions on a regular basis. There are only three occasions you need to do this: 1. When you have just installed something that required you to run an Installer, rather than just copying some software to a folder. This should be done for both Apple and non-Apple software. (Note Office 2008 will come with an Installer this time) 2. When you have been working on your OS X files or folders while booted from OS 9, or remote...

Using More than 7 if functions in a formula
Help--I am totally new at this feature of spreadsheets. I am trying to create a formula that needs more than 7 if functions i a formula. I want to be able to type in a weight and it will automatically choos the value that should be assigned to it. The weights range from 110 t 260. I have found out that you can only use 7 IF functions in formula. I have put in the following formula up to the 7th I function, but don't know where to go from here: If(B4=110,.656,if(b4=111,.659,if(b4=112,.661,if(b4=113,.665,if(b4=114,.669,if(b4=115,.673,if(b4=116,.678 I have read something about VLooku...

Preventing users from using preview pane?
Is it possible to remove the preview pane option from the view menu or prevent the user from being able to use it? You can set a policy to disable the menu command. The command bar ID should be 5514. The policy templates can be found in the Office Resource Kit http://www.microsoft.com/office/ork. You will want to download and install the Office Core Tools to get the policy templates. I don't think the policy is 100% bullet proof because it only turns off the menu item(s). If the user already had the preview pane enabled it will still be enabled when the policy is turned on. Please let ...

using screen...
Hi, I have problem with the query in the cascade combobox when the form name change. Is there a way to replace the following using screen.activeform [Forms]![frmCoFundReview]![Partner] => screen.activeform.[Partner] ? SF Not that I know. You could use a separate query for each form. Each query would have the correct form name for the combo box. Jeanette Cunningham MS Access MVP -- Melbourne Victoria Australia "SF" <samnangs@pactcambodia.org> wrote in message news:u%23z%23g6iyKHA.2644@TK2MSFTNGP04.phx.gbl... > Hi, > > I have probl...

Use Richedit v2.0 with VC5.0/MFC4.2?
Hi. I'm using VC 5.0 with MFC 4.2 and would like to add the extra functionality of the RichEdit v2.0 control. The supplied copy of 'RichEdit.h' supports v2.0, but if, (as recommended by MS in one of their articles), I change the class name in the *.rc file from "RICHEDIT" to "RichEdit20", then call 'AfxInitRichEdit2()', this function is not recognised, so 'RichEd20.dll' does not get loaded. (Obviously 'AfxInitRichEdit2()' doesn't exist in MFC 4.2) Is there a way to use RichEdit v2.0 under these conditions? Any advice welcome,...

ISSUE: Using VBA to Delete a Column
Hello all, I'm using a VBA routine that creates a copy of a worksheet under a different filename. The routine needs to delete column (D) before saving the new file, however column D passes through a group of merged cells (A1 through D1). When the command reaches this point: > Columns("D:D").Select > Range("D2").Activate, the entire range of cells from A:D are selected. I could use the mouse to manually select column D and delete it, but why wont VBA perform in the same manner. Here is the entire sub if it helps: Sub Create_ECP_Copy() ' ' ...

Using search to find an email
If I do a search for an email in Outlook 2003 and choose all mail folders, is there a way to see what folder the item was found in? It seems to just show me the message, but not the location, so I don't actually know where it is..... Thanks If you add fields to the advanced search window, it will show you where the item was found. --� Milly Staples [MVP - Outlook] Post all replies to the group to keep the discussion intact. Due to the (insert latest virus name here) virus, all mail sent to my personal account will be deleted without reading. After furious head scratching, Sande...

Replace using wildcards
Hi, I'm a newbie to Excel and this group so please excuse my ignorance. I'm trying to do what should be a pretty simple find and replace. I want to replace: base=xyz*cntry=123*type=simple wist base=differentbase*cntry=123*type=simple I have to include the type field in my search and the asterik's are part of the text, not wildcards. The only thing I want to change is the base. I put this in for the search criteria: base=xyz*cnty=???*type=simple This finds all the lines I'm looking for so, so far, so good. For the replace string, I use this: base=differentbase*cntry=???*ty...

Excel file in use error
This error occurs with spreadsheets which contain macros, they cannot be ammended nor deleted by a network administrator! any ideas???? ...

How to change account and password for services by using Powershell?
Hi all! I would like to know how to use Powershell to change account and password for services. Thanks, Felipe Being more specific, I would like to change the account and password for two specific services using Powershell. "Carlos Felipe Fran�a da Fonseca" <carlosfelipefranca@gmail.com> wrote in message news:#SbMd8e#KHA.5592@TK2MSFTNGP02.phx.gbl... > Hi all! > > I would like to know how to use Powershell to change account and password > for services. > > Thanks, > > Felipe Can you be even more specific? Do you mean ...

Destryoing modeless dialog in a modeless thread causes deadlock
Hello there, I've created a user-interface thread to manage modeless dialog. I use it to display comforting "Please wait..." messages to the user while worker threads do lengthy operations (in this case, tasking robotics, but that's not important). So, here's a use case: The user initiates a long process by selecting a menu item. In the main GUI message handler, a worker thread is created to do perform the operation. The message handler returns. The worker thread creates a user-interface thread, which creates a modeless dialog. Any time the worker thread needs t...

Creating and pasting using VB
I need to create an email and paste some data already selected in excel into the body. I have just started to attempt this so if I need to add mapi or anything like that please let me know. Any help would be very helpful.... Thanks, Matt If you copy straight from an Excel sheet to an email, you will be pasting an object and that can be a nuisance, particularly if you need to edit the contents before sending it. I simply paste it to Word first, then copy it from Word into the email. This may not suit your needs though. HTH Otto <mewilh0@gmail.com> wrote in message news:1145...

Use text in a cell to reference a sheet
Hi - I'm trying to reference the text of a cell to reference another sheet. Example: D3 is a text cell that has contents of "Sheet4" Is it possible to use the text in that cell to reference another sheet Example: =D3!A1 (So the end result would be equivalent to "=Sheet4!A1" without havin the sheet explicitly stated) Of course, the example above does not work, so I tried various ways o dereferencing the D3 cell to make it work - putting it in quotes putting it in parentheses, using CELL(contents,D3), etc. I couln' seem to come up with anything that would prop...

how do i set up a HTML newsletter to use with a mass email tool
Not with Publisher. Pub doesn't do a simple HTML document. -- JoAnn Paules MVP Microsoft [Publisher] "virtuallysavvy" <virtuallysavvy@discussions.microsoft.com> wrote in message news:9DBEDDD2-A6F3-4CF8-BB19-44FE7F07FB1F@microsoft.com... > A crystal ball would help you and maybe us. This white space is for you to describe your problem and what programs you might be using. -- John G Wot's Your Real Problem? I have created a newsletter in publisher and converted to .html. I now need to download the html to the mass email tool that I use, but h...

Using INSERT with joined Tables
I need to INSERT an additional address in my "ADDRESS" table for my students. But I need to join the ADDRESS table with my "ACADEMIC" table which has the Year/Term information to meet my criteria. My CRITERIA is: Admit Year must be = "2006" Admit Term must be = "Summer1" Admit Session must be = "01" Address Type must NOT BE EQUAL TO "PERM" I don't want to insert a new record for everyone, only those students who meet the criteria above. My SCRIPT looks like this:- INSERT INTO [Campus6_test].[dbo].academi...

Copying File using WebDAV
Hi Can anybody plz tell me how to copy files using WebDAV. I want to copy files go.asp from my localpath http://servername/webdav/go.asp to http://servername/exchange/administrator/foldername/go.asp It gives me error saying " The remote server returned an error: (403) Forbidden". and here is my code Dim Request As System.Net.HttpWebRequest Dim httpResponse As System.Net.HttpWebResponse Dim MyCredentialCache As System.Net.CredentialCache Request = CType(System.Net.WebRequest.Create(strSrcURI), _ System.Net.HttpWebRequest) ' Add the network credentials to the request. '...

OWA-SSL: Should I use 3rd party certificate or create own CA
My partner and I are debating the use of a third party certificate (like Verisign) or the creation of our own Certificate Authority. We want our users to access OWA via ssl. I thought we should use third part certs because then we wouldn't have to worry about browsers having or not having our public key. I thought we would have to install that key on each machine that someone wanted to use to access OWA. My partner thinks that we could create our own CA using Windows 2000 server and create the certs. He believes that IE would already have the public key for certs created by our M...

USE TAXES
What is the best implentation to track Use Tax in Great Plains? I don't know if this is the best, but here's what I do. I set up a credit card called USE TAX using the comptroller as the associated vendor. When I buy something from a vendor I calculate the use tax and then pay the tax part using the credit card. The balance is what I really owe the vendor. GPlains automatically creates a payable for me to the comptroller and I'm good to go. Leslie "Ravi" wrote: > What is the best implentation to track Use Tax in Great Plains? > > ...

Rule Changes Received Date Using IMAP
I have Outlook 2003 running on XP with the latest updates and service packs. In Outlook I have an Exchange account and an IMAP account. Whenever I try to run any rule on the Inbox of my IMAP mail, it changes the Received Date listing to the current date on about half of my messages. When I open one of these incorrectly dated emails, the date shown in the message is correct and the date changes to the proper date in the listing of emails. Also, if I remove the IMAP account and then re-add it, the Inbox messages once again have the correct date. I've searched the web over and have found ...

Deadlock Problem
Dear All i m using SQL 2000 i have following table structure create table mytab (Fid varchar(16) Primary Key, Picture_1 image, Picture_2 image, Picture_3 image, Entry_time datetime) Data base is hosted on a server with 2 quad core processors and 8 gb Ram. more than 200 user insert data into the table through a front end application more than 30000 records enter daily in this table. data base is in Simple recovery mode. user experience deadlock during this operation. there is no data fragmentation in the table as it is removed daily. How can the performance be increase...

how to use StgOpenStorageEx
Hi all, when i use StgOpenStorageEx(L"C:\\myfile.xml", .... ), it work well but i use StgOpenStorageEx( lpszWFile, ), not work (see code below) any idea? i convert CString to WCHAR incorrect? void changeInfo(CString sFileName) { IPropertySetStorage *pPropSetStg = NULL; IPropertyStorage *pPropStg = NULL; PROPSPEC propspec; PROPVARIANT propWrite; PROPVARIANT propRead; HRESULT hr = S_OK; WCHAR* lpszWFile = new WCHAR[MAX_PATH]; CFile cFile; if ( cFile.Open(sFileName, CFile::modeRead) ) { sFileName = cFile.GetFilePath(); cFile.Close(); } else return; LPTSTR lpStr ...

Inserting the values of a formula using vb
HI All, Do you know where the error is below Thanks for any help With Worksheets("tblFaxMailBox").Range("F2:F" & LASTROW) .Formula= "= NETWORKDAYS(RC[-2],RC[-4],Holiday!R2C[-4]:R11C[-4])" .Value = .Value End With HI I found the error. I needed to add R1C1 "ram" wrote: > HI All, > > Do you know where the error is below > > Thanks for any help > > With Worksheets("tblFaxMailBox").Range("F2:F" & LASTROW) > .Formula= > "= NETWORKDAYS(RC[-2],RC[-4],H...

Select sentence using a variable
Hi, In Excel 2003 I'm trying to write a query sentence to get data from a dbf table where table.date_mov is newer than a value (a cell in the worksheet which I named as date_min ) How can I get it? TIA ramonvi Done! no problem, I needed to sleep for a while! ramonvi "ramonvi" wrote: > Hi, > > In Excel 2003 I'm trying to write a query sentence to get data from a dbf > table where table.date_mov is newer than a value (a cell in the worksheet > which I named as date_min ) > > How can I get it? > > TIA > ramonvi ...

UK PostCodes > inserting values from Excel using Map
Guess I'm being thick. Two colums, one postcodes, one data. I want to use "MAP" to show the values geographically.... I've installed the "globe", having trouble finding the instructions.... can anyone point me in the correct direction? ta ...