I know C++11 added support for threads. For example:
#include <iostream> #include <thread> void bar() { std::cout << "bar()\n"; } int main() { std::thread thread(bar); thread.join(); return 0; }
However, is there a way to execute the bar
function in a separate process? If not, is there any discussion on whether such a feature should be added?
Note: I'm aware of the possibility of using platform independent libraries and I'm just curious if C++ supports this directly or will in the future.
A process is a container for a set of resources used while executing a program. A process includes the following: Private virtual address space. A program.
We recommend choosing the latest standard “ISO C++ Latest (/std:c++latest)”, which as of the time of writing is the setting for C++20 support.
The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators.
No, the c++ standard (particularly C++11) doesn't have any notion of a process (hence I can't give you a more reasonable reference here as a search result from the most popular and currently most up to date c++ documentation site).
I'm also not aware that process support is planned for the next standard version C++-17 (aka C++-1z). At least the Wikipedia Site doesn't mention it.
There is a popular implementation that was proposed for boost, but that never was drawn for a C++ standard proposal.
You usually can't write portable code to run on bare metal systems, where only one process exists.
However, is there a way to execute the
bar()
function in a separate process?
The simplest option to do that is to fallback to fork()
and wait()
as specified by the POSIX Open Group:
#include <iostream> #include <unistd.h> #include <sys/wait.h> void bar() { std::cout << "bar()\n"; } int main(int argc, char **argv) { pid_t pid = fork(); if (pid == 0) { // child process bar(); } else if (pid > 0) { // parent process wait(NULL); } else { // fork failed std::cerr << "fork() failed!" << std::endl; return 1; } return 0; }
Though I don't see much of a point to create an extra process to execute a simple function. Creating a process creates a lot of overhead you don't want in such case.
Well, if you want to start another program using functions from the exec()
function family that's a different use case.
I'd recommend sticking to std::thread
s for your example.
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