c 如何獲取多執行緒的返回值?

2022-06-14 06:24:13 字數 2476 閱讀 8705

//簡單的 c++11 執行緒,簡單方便,成員函式隨便呼叫,非成員函式也一樣,如需要獲取返回時,請自行使用條件變數

std::thread run([&]());

run.detach();

繼承類方式多執行緒

#include #include #include class thread 

} void statr()

} void requestinterruption()

bool isinterruptionrequested()

protected:

virtual void run()

std::cout << "run end" << std::endl;

}private:

std::thread m_thread;

std::atomic_flag m_requestinterruption = atomic_flag_init;

};

原子鎖(atomic)-搶占式

#include #include #include #include std::atomic_flag flag = atomic_flag_init;

void process()

/* 執行緒保護區域(zone to portect) */

// task

//釋放鎖

flag.clear(std::memory_order_release);

}

auto run=std::async([&]());

run.get();

auto run=std::async(std::launch::async,[&]());

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 #include #include //執行緒庫

#include #include #includestd::mutex g_display_mutex;

void foo()

void threadtest()

int sum(int &x, int &y)

int sums(int x, int y,int z)

int main()

std::cout << std::string(info) << " 執行緒id:" << std::this_thread::get_id() << " sum:" << sum << std::endl;

return sum;

}; // 非同步求值

std::futurecalc_async = std::async(std::launch::async,fn,"非同步求值");

// 惰性求值

std::futurecalc_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()

; for (int i = 0; i < 10; ++i)

cv.notify_all();

getchar();

return 0;

}

執行緒呼叫類成員函式,需要顯示的傳遞成員函式預設傳遞的this指標,即當前例項化物件指標,後面再傳遞你需要的引數。

class asynctest

int calc(int x,int y,int &result)

};int main()

return 0;

}

Python 獲取多執行緒獲取返回值

1.通過重寫thread類,自定義乙個get result 方法 重新定義帶返回值的執行緒類 from threading import thread from time import sleep,time class mythread thread def init self,func,args ...

Python多執行緒獲取返回值

在使用多執行緒的時候難免想要獲取其操作完的返回值進行其他操作,下面的方法以作參考 一,首先重寫threading類,使其滿足呼叫特定的方法獲取其返回值 import threading class mythread threading.thread 重寫多執行緒,使其能夠返回值 def init s...

Python多執行緒獲取返回值

在使用多執行緒的時候難免想要獲取其操作完的返回值進行其他操作,下面的方法以作參考 一,首先重寫threading類,使其滿足呼叫特定的方法獲取其返回值 import threadingclass mythread threading.thread 重寫多執行緒,使其能夠返回值 def init se...