c++ 如何獲取多線程的返回值?


//簡單的 c++11 線程,簡單方便,成員函數隨便調用,非成員函數也一樣,如需要獲取返回時,請自行使用條件變量
    std::thread run([&](){
        //執行一些耗時的操作
        return 0;
    });
    run.detach();
    auto run=std::async([&](){
        return this->執行一些耗時的操作成員函數();
    });
    run.get();
    auto run=std::async(std::launch::async,[&](){
        return this->執行一些耗時的操作成員函數();
    });
    run.get();
auto future = std::async(std::launch::deferred, function, arg1, arg2);
 
// some time later, possibly in another thread:
future.get(); // calls the function with the arguments
// Console.cpp : 定義控制台應用程序的入口點。
//

#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <thread>	//線程庫
#include <future>
#include <mutex>
#include<numeric>

std::mutex g_display_mutex;

void foo()
{
	std::thread::id this_id = std::this_thread::get_id();

	g_display_mutex.lock();
	std::cout << "thread " << this_id << " sleeping...\n";
	g_display_mutex.unlock();

	std::this_thread::sleep_for(std::chrono::seconds(0));
}

void threadTest()
{
	std::thread t1(foo);
	std::thread t2(foo);
	t1.join();
	t2.join();
}

int sum(int &x, int &y)
{
	std::cout << std::hex << std::this_thread::get_id() << std::endl;
	std::this_thread::sleep_for(std::chrono::seconds(1));
	return x + y;
}

int sums(int x, int y,int z)
{
	std::cout << std::hex << std::this_thread::get_id() << std::endl;
	std::this_thread::sleep_for(std::chrono::seconds(1));
	return x + y + z;
}


int main()
{
	
	int x = 3;
	int y = 4;
	std::future<int> fu = std::async(sums, 3, 4,5);
	//std::future<int> fu = std::async(sum,std::ref(x),std::ref(y));
	std::cout << fu.get() << std::endl;

	//獲取當前計算機線程數量
	std::cout << std::thread::hardware_concurrency() << std::endl;
	//獲取當前線程ID
	std::cout << std::hex <<std::this_thread::get_id() << std::endl;
	system("pause");
    return 0;
}

#include <thread>
#include <memory>
#include <string>
#include <future>
#include <mutex>
#include<numeric>
#include <cstdlib>
#include <iostream>

int main()
{
	std::cout << "start 當前 main 線程ID:" << std::this_thread::get_id() << std::endl;

	// 定義函數原型
	auto fn = [](const char *info)->int {
		int sum = 0;
		for (int i = 0; i < 1000000000; ++i) {
			++sum;
		}
		std::cout << std::string(info) << " 線程ID:" << std::this_thread::get_id() << " sum:" << sum << std::endl;
		return sum;
	};

	// 異步求值
	std::future<int> calc_async = std::async(std::launch::async,fn,"異步求值");

	// 惰性求值
	std::future<int> calc_deferred = std::async(std::launch::deferred,fn,"惰性求值");

	std::cout << "end 當前 main 線程ID:" << std::this_thread::get_id() << std::endl;

	// 啟動線程
	std::cout << "惰性求值結果:" << calc_deferred.get() << std::endl;

	/*!
		運行以上代碼可以看出,惰性求值 方式需要調用 calc_deferred.get() 才會執行該函數,並且線程id和主線程是一致的.
		而異步求值會自動運行,當然你想獲取結果也可以使用 calc_async.get();
	*/
	
	getchar();
    return 0;
}
int main()
{
	std::cout << "當前線程ID:" << std::this_thread::get_id() << std::endl;

	std::mutex mutex;//互斥鎖
	std::condition_variable cv;//信號量

	auto fn_worker_thread = [&](int id) {
		std::unique_lock<std::mutex> lock(mutex);
		cv.wait(lock);

		std::cout << "線程ID:" << std::this_thread::get_id() << "lock id:" << id << std::endl;
	};

	for (int i = 0; i < 10; ++i) {
		std::thread run(fn_worker_thread,i);
		run.detach();
	}

	//cv.notify_one();
	cv.notify_all();

	getchar();
    return 0;
}

線程調用類成員函數,需要顯示的傳遞成員函數默認傳遞的 this 指針,即當前實例化對象指針,后面再傳遞你需要的參數。

class AsyncTest{
public:
    void print(){
        fprintf(stderr,"print\r\n");
    }
    int calc(int x,int y,int &result){
        result = x + y;
        return result;
    }
};

int main()
{
    AsyncTest test;

    {// call function void print()
        std::future<void> async = std::async(std::launch::async,&AsyncTest::print,&test);
        async.get();
    }

    {// call function int calc(int x,int y,int &result)
        int result = 0;
        int x = 3;
        int y = 4;
        std::future<int> async = std::async(std::launch::async,&AsyncTest::calc,&test,x,y,std::ref(result));
        int output = async.get();
        fprintf(stderr,"x + y = %d output = %d",result,output);
    }

    return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM