In case of Linux, for time functions we have a _r versions Ex: localtime has localtime_r, but in Windows I am unable to find some such functions. Are the Windows time functions inherently thread-safe?
With Microsoft Visual Studio you have a choice of c-runtimes to use: typically they were:
static single threaded library (libc)
Static multithreaded library (libcmt)
dynamic multithreaded library (msvcrt)
The multithreaded libraries are thread safe. The single threaded library was last seen in MSVC 2005 and has been dropped from MSVC 2008.
The dll runtime (msvcrt.dll) just has to be thread safe - As the implementation is in a dll and therefore shared between multiple other modules in the process, all of which could be using worker threads, It has to be threadsafe as there would be no sane way to design an application to use it otherwise.
On windows the non-_r functions are thread safe because they use thread-local storage for the buffer. See e.g. http://msdn.microsoft.com/en-us/library/bf12f0hc(VS.80).aspx
I think that Windows localtime_s is thread safe: http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx - at least when using MS CRT
I think that they aren't ThreadSafe and there is no _r version. But correct me if I'm wrong.
Maybe it's better if you use the own Windows functions, like
GetSystemTime, GetSystemTimeAsFileTime or GetLocalTime
Related
I was looking at the NtDll export table on my Windows 10 computer, and I found that it exports standard C runtime functions, like memcpy, sprintf, strlen, etc.
Does that mean that I can call them dynamically at runtime through LoadLibrary and GetProcAddress? Is this guaranteed to be the case for every Windows version?
If so, it is possible to drop the C runtime library altogether (by just using the CRT functions from NtDll), therefore making my program smaller?
There is absolutely no reason to call these undocumented functions exported by NtDll. Windows exports all of the essential C runtime functions as documented wrappers from the standard system libraries, namely Kernel32. If you absolutely cannot link to the C Runtime Library*, then you should be calling these functions. For memory, you have the basic HeapAlloc and HeapFree (or perhaps VirtualAlloc and VirtualFree), ZeroMemory, FillMemory, MoveMemory, CopyMemory, etc. For string manipulation, the important CRT functions are all there, prefixed with an l: lstrlen, lstrcat, lstrcpy, lstrcmp, etc. The odd man out is wsprintf (and its brother wvsprintf), which not only has a different prefix but also doesn't support floating-point values (Windows itself had no floating-point code in the early days when these functions were first exported and documented.) There are a variety of other helper functions, too, that replicate functionality in the CRT, like IsCharLower, CharLower, CharLowerBuff, etc.
Here is an old knowledge base article that documents some of the Win32 Equivalents for C Run-Time Functions. There are likely other relevant Win32 functions that you would probably need if you were re-implementing the functionality of the CRT, but these are the direct, drop-in replacements.
Some of these are absolutely required by the infrastructure of the operating system, and would be called internally by any CRT implementation. This category includes things like HeapAlloc and HeapFree, which are the responsibility of the operating system. A runtime library only wraps those, providing a nice standard-C interface and some other niceties on top of the nitty-gritty OS-level details. Others, like the string manipulation functions, are just exported wrappers around an internal Windows version of the CRT (except that it's a really old version of the CRT, fixed back at some time in history, save for possibly major security holes that have gotten patched over the years). Still others are almost completely superfluous, or seem so, like ZeroMemory and MoveMemory, but are actually exported so that they can be used from environments where there is no C Runtime Library, like classic Visual Basic (VB 6).
It is also interesting to point out that many of the "simple" C Runtime Library functions are implemented by Microsoft's (and other vendors') compiler as intrinsic functions, with special handling. This means that they can be highly optimized. Basically, the relevant object code is emitted inline, directly in your application's binary, avoiding the need for a potentially expensive function call. Allowing the compiler to generate inlined code for something like strlen, that gets called all the time, will almost undoubtedly lead to better performance than having to pay the cost of a function call to one of the exported Windows APIs. There is no way for the compiler to "inline" lstrlen; it gets called just like any other function. This gets you back to the classic tradeoff between speed and size. Sometimes a smaller binary is faster, but sometimes it's not. Not having to link the CRT will produce a smaller binary, since it uses function calls rather than inline implementations, but probably won't produce faster code in the general case.
* However, you really should be linking to the C Runtime Library bundled with your compiler, for a variety of reasons, not the least of which is security updates that can be distributed to all versions of the operating system via updated versions of the runtime libraries. You have to have a really good reason not to use the CRT, such as if you are trying to build the world's smallest executable. And not having these functions available will only be the first of your hurdles. The CRT handles a lot of stuff for you that you don't normally even have to think about, like getting the process up and running, setting up a standard C or C++ environment, parsing the command line arguments, running static initializers, implementing constructors and destructors (if you're writing C++), supporting structured exception handling (SEH, which is used for C++ exceptions, too) and so on. I have gotten a simple C app to compile without a dependency on the CRT, but it took quite a bit of fiddling, and I certainly wouldn't recommend it for anything remotely serious. Matthew Wilson wrote an article a long time ago about Avoiding the Visual C++ Runtime Library. It is largely out of date, because it focuses on the Visual C++ 6 development environment, but a lot of the big picture stuff is still relevant. Matt Pietrek wrote an article about this in the Microsoft Journal a long while ago, too. The title was "Under the Hood: Reduce EXE and DLL Size with LIBCTINY.LIB". A copy can still be found on MSDN and, in case that becomes inaccessible during one of Microsoft's reorganizations, on the Wayback Machine. (Hat tip to IInspectable and Gertjan Brouwer for digging up the links!)
If your concern is just the need to distribute the C Runtime Library DLL(s) alongside your application, you can consider statically linking to the CRT. This embeds the code into your executable, and eliminates the requirement for the separate DLLs. Again, this bloats your executable, but does make it simpler to deploy without the need for an installer or even a ZIP file. The big caveat of this, naturally, is that you cannot benefit to incremental security updates to the CRT DLLs; you have to recompile and redistribute the application to get those fixes. For toy apps with no other dependencies, I often choose to statically link; otherwise, dynamically linking is still the recommended scenario.
There are some C runtime functions in NtDll. According to Windows Internals these are limited to string manipulation functions. There are other equivalents such as using HeapAlloc instead of malloc, so you may get away with it depending on your requirements.
Although these functions are acknowledged by Microsoft publications and have been used for many years by the kernel programmers, they are not part of the official Windows API and you should not use of them for anything other than toy or demo programs as their presence and function may change.
You may want to read a discussion of the option for doing this for the Rust language here.
Does that mean that I can call them dynamically at runtime through
LoadLibrary and GetProcAddress?
yes. even more - why not use ntdll.lib (or ntdllp.lib) for static binding to ntdll ? and after this you can direct call this functions without any GetProcAddress
Is this guaranteed to be the case for every Windows version?
from nt4 to win10 exist many C runtime functions in ntdll, but it set is different. usual it grow from version to version. but some of then less functional compare msvcrt.dll . say for example printf from ntdll not support floating point format, but in general functional is same
it is possible to drop the C runtime library altogether (by just using
the CRT functions from NtDll), therefore making my program smaller?
yes, this is 100% possible.
I have a function, lets say, callMe(args). I would like to be able to call my function 100 times in the same time (concurrent programing). My function is written in plain C. I want to make it concurrent for Windows and Linux.
Is there any built in support for this in standard C library? Or can you provide some advices, how should I do this in Linux/Windows?
Is pthread good for Linux environments for this?
You can't write a concurrent program in pure standard C99. Concurrent programming is not in standard C99; it requires some operating system specific libraries. However, the latest C11 standard (which has very few implementations today, February 2014 - I know none!) is beginning to add support for threads. On Linux systems I would suggest today to stick to pthreads.
You could use a cross-platform library (like glib from GTK) to ease porting between Windows and Linux. On Linux, it is wrapping pthreads.
I don't know Windows, but Glib -and GTK for GUI applications- is rumored to enable source-compatible coding between Windows & Linux
If your computation is embarrassingly data parallel (like some matrix numerical computations are), consider also OpenCL (notably because it can run on GPGPUs) or OpenMP. If it fits in a message passing paradigm, consider MPI
OpenCL, OpenMP, MPI are rumored to enable source-compatible coding for Linux and for Windows.
In C++11 (which is a different language than C) you have thread support, and the GCC 4.8.2 compiler is supporting them quite well. And Qt or Poco or Boost is a cross-platform C++ library, notably wrapping concurrent primitives.
Whatever concurrent mechanism you are using, beware of synchronization issues.
You always have synchronization with concurrency, at least to wait for the results of each concurrent or parallel sub-computation
You have to use different functions for different platforms.
Its similar like different browsers uses different kind of css property names.
So for linux/mac you can use pthread
And for windows you use CreateThread
Is multithreading supported in C? If yes, then how do I try? Is there any open source library that lets me do it and is the library supported on Mac OS X?
I haven't found any article saying that it's supported.
C is not intrinsically a multithreaded language; however there are many libraries which add threading functionality.
pthreads is a library compatible with any POSIX system, so it is supported on OSX. I found https://hpc-tutorials.llnl.gov/posix/ to be a good place to start.
Win32 has a threading library for C described at https://learn.microsoft.com/en-us/cpp/parallel/multithreading-with-c-and-win32.
Glib adds threading supported, and has the advantage of being completely cross-platform, as long as glib is installed on the target machine. There is some information here: http://developer.gnome.org/glib/2.28/glib-Threads.html
C has no concept whatever of threads. There is no thread support in C Standard. There are extensions available that can implement multi threading - one of which is pthreads.
Be aware because C language has no natural support of threads you as the programmer have to take care of everything and you will not be protected against any of the pitfalls of multi-threaded programming.
the new dialect - C1X, will offer multi-threading out of the box, as stated from wikipedia:
Multithreading support (_Thread_local storage-class specifier, header including thread creation/management functions, mutex, condition variable and thread-specific storage functionality, as well as the _Atomic type qualifier and for uninterruptible object access).
currently of courae as mentioned above, multi-threading is not supported in the newest dialect of c - C99
Pthreads. OSX has posix support.
I would guess that the majority of multithreaded programming on Mac OS X is done in Objective-C or C++, not plain C. (I realize that this isn't exactly an answer to the question that you asked, but you might want to know about alternatives.) In Objective-C, you'd use NSThread or, in Snow Leopard and later, Grand Central Dispatch (GCD). In C++, you could use the threads library from boost.org, which has the advantage of being cross-platform.
I have just started reading about threading in C, using pthreads. I know that Pthreads are available for Windows, but do multithreaded WIndows based C/C++ applications mostly use Pthreads?
Also in Unix/Linux are Pthreads the main way developers write multithreaded C/C++ code?
No, most will use the thread abstraction of the application/gui library they are using, e.g. MFC. Or in the plain C case, using the windows API directly.
Pthreads stands for "POSIX" threads, which is basically standarized unix(-like), a standard that has little meaning on Windows outside dedicated POSIX emulations like cygwin.
The new C++ Standard, C++11, has support for portable threads. I'd definitely go with that, except that Visual Studio hasn't implemented them yet.
What is the relationship between the Windows API and the C run time library?
In a nutshell: The Windows API contains all the functions defined specifically for Windows. The C run-time library contains all the functions that are required by standard C.
The physical libraries that implement these functions may be a single file (library), split across two separate libraries or split into many libraries, depending on the operating system and the actual API/service you are using.
For example, when creating files, the C standard includes the function:
fopen
to open and create files, etc., while the Win32 API (for example) defines functions like:
CreateFile
to create and manipulate files. The first one will be available wherever a standard C run-time library is available while the second one will only be available on a Windows machine that supports the Win32 API.
If you mean the standard C library (msvcrt.dll I assume). Then not much at all. The majority of the windows API is implemented in separate dlls (very much of it is in user32.dll or kernel32.dll). In fact, some of these functions in the Windows API are just thin wrappers around system calls where the actual work is done in the kernel itself.
Also, as ocdecio said, it is entirely reasonable to assume that certain parts of the C standard library are implemented using windows APIs. And for certain cases like string manipulations, vice versa.
EDIT: since which dlls are implemented in terms of others has come into question, i've checked with dependancy walker and here is my findings:
kernel32.dll depends on:
ntdll.dll
user32.dll depends on:
gdi32.dll
kernel32
ntdll.dll
advapi.dll
msimg32.dll
powerprof.dll (this dll references msvcrt.dll for some string functions)
winsta.dll
msvcrt.dll depends on:
kernel32.dll (yes it does have imports for CreateFileA)
ntdll.dll
based off of this, I believe that msvcrt is build on top of the win32 API.
Win32 is a completely different beast to the CRT.
CRT is something that needs to be linked into your project when you use C or C++ functions/features (such as printf or cout).
Win32 is a set of libraries that need to be linked into your project when you use Windows features (like GetWindowText).
What they are:
The Windows API is the API exported by the Microsoft Windows[TM] Operating System
The C run time library is the "standard library" which is shipped with the C compiler by the compiler vendor, and which is available on whichever/any operating system (for example, Unix) is targetted by the compiler
What their relationship is:
They are distinct, but both equally available to C++ applications running on Windows
On Windows, the C standard library is implemented by invoking the underlying Windows API (to allocate memory, open files, etc.).
C run time library is based on the Windows API
Unix System calls are analogy with Windows API.