CRT thread-safe when called from C-Sharp

B

Boris

Hi,

Background: Let's say, there's a DLL - A.DLL (native code) that exports
function Foo(). Foo() calls some C-runtime library functions. Some other
native code (for example, in an EXE) calls Foo() from multiple threads.
There're 2 requirements to prevent multi-threading related problems inside
CRT:

1. A.DLL should be built using multi-threaded version of CRT;
2. Threads that call Foo() must be started via _beginthread/_beginthreadex,
but not via CreateThread().

I have a question on calling Foo() inside A.DLL from C# code: would calling
CRT functions by Foo() be still thread safe, if A.DLL was compiled/linked
with multi-threaded version of CRT and the below C# caller code was used?

public class SomeClass
{
...
[System.Runtime.InteropServices.DllImport("A.DLL")]
public static extern void Foo();
...
private void MyThreadFunc()
{
Foo();
}
private Thread m_thread;
...
static void Main()
{
...
m_thread = new Thread(new ThreadStart(this.MyThreadFunc));
...
}
}


Thanks,
Boris
 
J

Jeroen Mostert

Background: Let's say, there's a DLL - A.DLL (native code) that exports
function Foo(). Foo() calls some C-runtime library functions. Some other
native code (for example, in an EXE) calls Foo() from multiple threads.
There're 2 requirements to prevent multi-threading related problems
inside CRT:

1. A.DLL should be built using multi-threaded version of CRT;
2. Threads that call Foo() must be started via
_beginthread/_beginthreadex, but not via CreateThread().
Requirement 2 is no longer really a requirement. See
http://support.microsoft.com/kb/104641/. Not using _beginthread*() causes a
small memory leak, but there are no threading problems. This is a good thing
too, because there would be no way for the CLR to call the "correct" CRT
version of _beginthread*() -- DLLs containing unmanaged code are not loaded
until functions in them are invoked, and by that point it's too late to call
_beginthread*().
 
B

Boris

Thanks a lot!

Jeroen Mostert said:
Requirement 2 is no longer really a requirement. See
http://support.microsoft.com/kb/104641/. Not using _beginthread*() causes
a small memory leak, but there are no threading problems. This is a good
thing too, because there would be no way for the CLR to call the "correct"
CRT version of _beginthread*() -- DLLs containing unmanaged code are not
loaded until functions in them are invoked, and by that point it's too
late to call _beginthread*().
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top