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

您好我开始在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 ++做multithreading的正确方法吗?

你可以看看未来的课程。 这是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'; }