Jak Sprawić żeby wykonywały się dwie funkcje na raz ?
Ostatnio zmodyfikowano 2017-08-21 19:05
MatexPL Temat założony przez niniejszego użytkownika |
Jak Sprawić żeby wykonywały się dwie funkcje na raz ? » 2017-08-20 20:33:42 Wszystko już w tytule |
|
karambaHZP |
» 2017-08-20 21:15:52 #include <future> #include <thread> #include <chrono> #include <random> #include <iostream> #include <exception>
int DoSomething( char ch ) { std::default_random_engine dre( ch ); std::uniform_int_distribution <> id( 10, 1000 ); for( int i = 0; i < 10; ++i ) { std::this_thread::sleep_for( std::chrono::microseconds( id( dre ) ) ); std::cout.put( ch ).flush(); } return ch; }
int Func1() { return DoSomething( '.' ); }
int Func2() { return DoSomething( '*' ); }
int main() { std::future < int > result1( std::async( Func1 ) ); int result2 = Func2(); int result = result1.get() + result2; std::cout << '\n' << result << std::endl; } Output: .**..**..**..**..**. 88 Np. uruchomienie dwóch funkcji asynchronicznie. Jedna w osobnym wątku, a druga w obecnym. Uruchomienie asynchroniczne nie jest gwarantowane jeśli nie będzie dostępnego dodatkowego wątku. |
|
mokrowski |
» 2017-08-21 19:05:30 Jeśli nie jest interesujące co zwracają, można tak: #include <iostream> #include <thread> #include <chrono>
using namespace std::chrono_literals;
void fun1() { for(;; ) { std::cout.put( '+' ).flush(); std::this_thread::sleep_for( 500ms ); } }
void fun2() { for(;; ) { std::cout.put( '-' ).flush(); std::this_thread::sleep_for( 300ms ); } }
int main() { std::thread( & fun1 ).detach(); std::thread( & fun2 ).detach(); std::this_thread::sleep_for( 5s ); std::cout.put( '\n' ); }
|
|
« 1 » |