From the C ++ 11 standard, features were introduced regarding concurrent programming. These features can be found in the files:
-
<conditional_variable>
-
<future>
-
<mutex>
-
<thread>
In this files you have access to several functions and classes that provide the basics for you to build competing applications.
Responding specifically to your Java equivalent questions:
Firstly we have to remember that ideologically C ++ and Java are very different languages, in C ++ object orientation is just another tool and is not usually imposed on the user. Therefore, for concurrent libraries, there is no requirement to create a class that inherits from Runnable
or Thread
.
This is a C ++ example of creating a std::thread
that runs the thread_main
function:
std::thread t{ thread_main };
thread_main
can be anything that can be invoked as a function that does not receive parameters and returns nothing.
Some examples of implementation:
// Função comum
void thread_main()
{
while (true)
{
std::cout << "Ola de outra thread.\n";
}
}
// Lambda
auto thread_main = []() {
while (true)
{
std::cout << "Ola de outra thread.\n";
}
};
Other differences in thread implementation in C ++:
-
std::thread
starts to run immediately. (As if calling the start
method of Java in the constructor)
- Before an object of type
std::thread
is destroyed it is mandatory to call one of the following methods:
-
std::thread::join
: blocks and waits for the thread to finish executing.
-
std::thread::detach
: frees the thread to continue running independently.
Regarding Java methods, there is only one direct equivalence:
-
Thread.yield
= std::this_thread::yield
In C ++ the notification functionality (signals) are implemented by a separate class, std::condition_variable
. Thus, we have the following equivalences:
-
Object.wait
:
-
Object.notify
:
-
Object.notifyAll
:
For the other features you asked for, there is no direct equivalence:
References: