Tôi đang sử dụng C++ 11 trên Mac OS Xcode 4.3.2 std :: async sử dụng cùng một chuỗi và mã của tôi không đạt được tính song song. Trong mẫu mã dưới đây tôi muốn tạo ra 10 chủ đề mới. Trong mỗi chủ đề tôi muốn tính căn bậc hai của biến đầu vào và đặt kết quả theo lời hứa. trong chức năng chính tôi muốn hiển thị các kết quả tính từ chủ đề. Tôi đang gọi std :: async với chính sách khởi động :: async, Vì vậy, tôi mong đợi nó để tạo ra một chủ đề mới (10 lần).std :: async sử dụng cùng một luồng và mã của tôi không đạt được tính song song.
#include <mutex>
#include <future>
#include <thread>
#include <vector>
#include <cmath>
#include <iostream>
using namespace std;
mutex iomutex;
void foo(int i, promise<double> &&prms)
{
this_thread::sleep_for(chrono::seconds(2));
prms.set_value(sqrt(i));
{
lock_guard<mutex> lg(iomutex);
cout << endl << "thread index=> " << i << ", id=> "<< this_thread::get_id();
}
}
int main()
{
{
lock_guard<mutex> lg(iomutex);
cout << endl << "main thread id=>"<< this_thread::get_id();
}
vector<future<double>> futureVec;
vector<promise<double>> prmsVec;
for (int i = 0; i < 10; ++i) {
promise<double> prms;
future<double> ftr = prms.get_future();
futureVec.push_back(move(ftr));
prmsVec.push_back(move(prms));
async(launch::async, foo, i, move(prmsVec[i]));
}
for (auto iter = futureVec.begin(); iter != futureVec.end(); ++iter) {
cout << endl << iter->get();
}
cout << endl << "done";
return 0;
}
Tuy nhiên nếu tôi sử dụng std :: thread, thì tôi có thể đạt được tính song song.
#include <mutex>
#include <future>
#include <thread>
#include <vector>
#include <cmath>
#include <iostream>
using namespace std;
mutex iomutex;
void foo(int i, promise<double> &&prms)
{
this_thread::sleep_for(chrono::seconds(2));
prms.set_value(sqrt(i));
{
lock_guard<mutex> lg(iomutex);
cout << endl << "thread index=> " << i << ", id=> "<< this_thread::get_id();
}
}
int main()
{
{
lock_guard<mutex> lg(iomutex);
cout << endl << "main thread id=>"<< this_thread::get_id();
}
vector<future<double>> futureVec;
vector<promise<double>> prmsVec;
vector<thread> thrdVec;
for (int i = 0; i < 10; ++i) {
promise<double> prms;
future<double> ftr = prms.get_future();
futureVec.push_back(move(ftr));
prmsVec.push_back(move(prms));
thread th(foo, i, move(prmsVec[i]));
thrdVec.push_back(move(th));
}
for (auto iter = futureVec.begin(); iter != futureVec.end(); ++iter) {
cout << endl << iter->get();
}
for (int i = 0; i < 10; ++i) {
thrdVec[i].join();
}
cout << endl << "done";
return 0;
}
Việc thực hiện của 'thread' thư viện trên GCC cũ là không thực sự chức năng. Hãy thử nó trên một cái gì đó không cổ đại. – pmr
@pmr: Tôi nghĩ Clang là trình biên dịch mặc định trong Xcode 4.2+? – ildjarn
@ildjarn Bạn nói đúng, dĩ nhiên. Tôi nhầm 4.3.2 có nghĩa là một phiên bản gcc (XCode sử dụng gcc 4.something trong một thời gian dài). – pmr