如何从c ++中的线程开始(返回)

时间:2017-04-06 14:41:55

标签: c++ windows multithreading c++11 codelite

您好我在Windows中使用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;
}

所以我的问题很简单,如何从thread1获取返回值,第二个问题是,这是在C ++中进行多线程处理的正确方法吗?

1 个答案:

答案 0 :(得分: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';
}