2017-04-06 1 views
1

こんにちは、私はWindowsのC++のスレッドから始めています。スレッドをC++で始める方法(返品)

#include <iostream> 
#include <thread> 
#include <windows.h> 
using namespace std; 
static const int num_threads = 2; 

CRITICAL_SECTION critSection; 
int thread1 (int id) { 

    EnterCriticalSection (&critSection); 
    cout <<"thread1 had id: " << id<<endl; 
    LeaveCriticalSection (&critSection); 
    return 15; 
} 

void thread2() { 
    EnterCriticalSection (&critSection); 
    cout << "Sleeping"<< endl; 
    LeaveCriticalSection (&critSection); 
    Sleep (20); 
    EnterCriticalSection (&critSection); 
    cout << "No more"<< endl; 
    LeaveCriticalSection (&critSection); 
} 

int main() { 
    thread t[num_threads]; 
    InitializeCriticalSection (&critSection); 

    t[0]=thread (thread2); 
    t[1] = thread (thread1, 1); 
    EnterCriticalSection (&critSection); 
    LeaveCriticalSection (&critSection); 
    t[0].join(); 
    t[1].join(); 


    DeleteCriticalSection (&critSection); 
    return 0; 
} 

ので、私の質問は簡単ですが、どのように私はスレッド1からの戻り値を取得し、2番目の質問があるんが、C++でマルチスレッド処理を行うには、この正しい方法はありますか?

+6

あなたは、このような[ 'のstd :: thread'](http://en.cppreference.com/w/cpp/thread/threadなどの標準的なスレッド化機能を使用することを検討すべきです)、['std :: mutex'](http://en.cppreference.com/w/cpp/thread/mutex)、[' std :: lock_guard'](http://en.cppreference.com/w/cpp/thread/lock_guard)と['std :: async'](http://en.cppreference.com/w/cpp/thread/async)を参照してください。 –

+0

私は何かを "返す"関数コールバックを使用したいと思います。 – xander

+0

スレッドは、参照パラメータを使用して結果を返すことができます。参照によって取られた追加の "return"引数を非同期関数に追加し、そのオブジェクトを使用して結果を格納することができます。単純なスレッド作業の場合は、 'std :: async'を使って関数の結果を返すことができます。 –

答えて

1

将来のクラスを見ることができます。これはcppreference.comからの例です:

#include <iostream> 
#include <future> 
#include <thread> 

int main() 
{ 
    // future from a packaged_task 
    std::packaged_task<int()> task([](){ return 7; }); // wrap the function 
    std::future<int> f1 = task.get_future(); // get a future 
    std::thread(std::move(task)).detach(); // launch on a thread 

    // future from an async() 
    std::future<int> f2 = std::async(std::launch::async, [](){ return 8; }); 

    // future from a promise 
    std::promise<int> p; 
    std::future<int> f3 = p.get_future(); 
    std::thread([&p]{ p.set_value_at_thread_exit(9); }).detach(); 

    std::cout << "Waiting..." << std::flush; 
    f1.wait(); 
    f2.wait(); 
    f3.wait(); 
    std::cout << "Done!\nResults are: " 
       << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n'; 
} 
関連する問題