Panel użytkownika
Nazwa użytkownika:
Hasło:
Nie masz jeszcze konta?

Jak Sprawić żeby wykonywały się dwie funkcje na raz ?

Ostatnio zmodyfikowano 2017-08-21 19:05
Autor Wiadomość
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
P-164142
karambaHZP
» 2017-08-20 21:15:52
C/C++
#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.
P-164145
mokrowski
» 2017-08-21 19:05:30
Jeśli nie jest interesujące co zwracają, można tak:
C/C++
#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' );
}
P-164178
« 1 »
  Strona 1 z 1