思考
Android開發(fā)中有子線程切換到主線程的方法,那么C++中是否也有同樣的方法呢?
經(jīng)過(guò)苦思冥想(半小時(shí)左右),我發(fā)現(xiàn)子線程切換到主線程不就是:1.子線程通知主線程需要執(zhí)行某個(gè)函數(shù)。2.同時(shí)子線程需要等待主線程把這個(gè)函數(shù)執(zhí)行完了才能繼續(xù)執(zhí)行。
于是我寫了下面這段代碼來(lái)解釋子線程切換主線程的原理,個(gè)人見(jiàn)解,僅供參考,歡迎溝通。
#include <iostream>
#include <thread>
#include <functional>
using namespace::std;
function<void()> mainCmdFunc = nullptr;
static void CmdToMainThread(function<void()> cmdFunc)
{
mainCmdFunc = cmdFunc;
while (mainCmdFunc != nullptr) {
}
}
template <typename F>
static void ExcuteLambdaFunc(F cmdFunc)
{
cmdFunc();
}
static void childThread()
{
cout << "老子是子線程" << endl;
while (true) {
CmdToMainThread([&]() {
cout << "老子是從子線程來(lái)的,牛皮不?" << endl;
});
cout << "老子從主線程回來(lái)了" << endl;
break;
}
}
int main()
{
thread *child_thread = new thread(childThread);
while (true) {
if (mainCmdFunc != nullptr) {
cout << "有子線程小弟有想在我家放點(diǎn)東西的想法,沒(méi)得問(wèn)題" << endl;
ExcuteLambdaFunc(mainCmdFunc);
mainCmdFunc = nullptr;
cout << "子線程小弟放完趕緊滾" << endl;
}
}
}