I was asked about this in an c++ developer position interview, what is the answer to this?
-pthread tells the compiler to link in the pthread library as well as configure the compilation for threads. Using the -lpthread option only causes the pthread library to be linked - the pre-defined macros don't get defined.
Windows does not support the pthreads standard natively, therefore the Pthreads4w project seeks to provide a portable and open-source wrapper implementation. It can also be used to port Unix software (which uses pthreads) with little or no modification to the Windows platform.
Pthreads is a very low-level API for working with threads. Thus, you have extremely fine-grained control over thread management (create/join/etc), mutexes, and so on. It's fairly bare-bones. On the other hand, OpenMP is much higher level, is more portable and doesn't limit you to using C.
The pthread_create() function is used to create a new thread, with attributes specified by attr, within a process. If attr is NULL, the default attributes are used. If the attributes specified by attr are modified later, the thread's attributes are not affected.
-pthread Adds support for multithreading with the pthreads library. This option sets flags for both the preprocessor and linker (man gcc). -lpthread comes in existence while linking there will be no influence while preprocessing.
-pthread tells the compiler to link in the pthread library as well as configure the compilation for threads. For example, the following shows the macros that get defined when the -pthread option gets used on the GCC package installed on my Ubuntu machine:
The first two also rely on pthread on platforms which support pthread. The only case where pthread could have an advantage would be if using some pthread-specific features not supported by std/boost::thread. Unless you continuously create lots of threads and use synchronization primitives a lot, there's no performance difference.
The Pthread interfaces described in this section are based on a subset of the application programming interfaces (APIs) defined in the POSIX standard (ANSI/IEEE Standard 1003.1, 1996 Edition OR ISO/IEC 9945-1: 1996) and the Single UNIX Specification, Version 2, 1997. The implementation of these APIs is not compliant with these standards.
I would have said:
If I wanted to create a portable cross-platform C++ binary, I'd use pthreads and use the pthread implementation for windows. If I wanted to create a windows-specific C++ binary, I'd use beginthread and avoid the 3rd party dependency on the pthread library.
If they really wanted to know the intricate internal details describing the differences between the two, you should think twice about working there. Unless it was for a reverse engineering job.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With