在gstreamer中做線程同步,這里分別用到了C++ condition_variable和glib的GCond和GMutex做線程同步,C++代碼用在外部代碼,glib的用法用在pipeline的代碼中。
創(chuàng)新互聯(lián)是專(zhuān)業(yè)的梁溪網(wǎng)站建設(shè)公司,梁溪接單;提供成都做網(wǎng)站、網(wǎng)站建設(shè),網(wǎng)頁(yè)設(shè)計(jì),網(wǎng)站設(shè)計(jì),建網(wǎng)站,PHP網(wǎng)站建設(shè)等專(zhuān)業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進(jìn)行梁溪網(wǎng)站開(kāi)發(fā)網(wǎng)頁(yè)制作和功能擴(kuò)展;專(zhuān)業(yè)做搜索引擎喜愛(ài)的網(wǎng)站,專(zhuān)業(yè)的做網(wǎng)站團(tuán)隊(duì),希望更多企業(yè)前來(lái)合作!C++ condition_variable的背景知識(shí)使用條件變量condition_variable做線程同步,可用于阻止一個(gè)線程或同時(shí)阻止多個(gè)線程,直到另一個(gè)線程修改共享變量(condition),并通知condition_variable,才會(huì)繼續(xù)執(zhí)行。
當(dāng)調(diào)用它的wait函數(shù)時(shí),它使用一個(gè)mutex來(lái)鎖定線程。使得該線程保持阻塞狀態(tài),直到被另一個(gè)線程調(diào)用同一個(gè)condition_variable對(duì)象上的notify函數(shù)才被喚醒。
condition_variable類(lèi)型的對(duì)象必須使用unique_lock等待。
wait
阻塞當(dāng)前線程,直到notify_all()或notify_one()被執(zhí)行。wait_for
阻塞當(dāng)前線程,直到條件變量被喚醒或在指定的超時(shí)持續(xù)時(shí)間之后。wait_until
阻塞當(dāng)前線程,直到喚醒條件變量或到達(dá)指定的時(shí)間點(diǎn)。本例中,ctrl+c的時(shí)候退出程序,所以下面signal_andler回調(diào)時(shí),執(zhí)行notify_all()
:
注冊(cè)signal_andler:
static std::mutex srv_mtx;
static std::condition_variable srv_cv;
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = signal_andler;
sigfillset(&sa.sa_mask);
sigaction(SIGINT, &sa, NULL);
notify_all:
void signal_andler(int sig) {std::unique_locklock(srv_mtx);
server_exit = 1;
srv_cv.notify_all();
}
wait的代碼:
std::unique_locklock(srv_mtx);
while (!server_exit) {printf("waiting ...\n");
srv_cv.wait(lock);
printf("done.\n");
}
gstreamer mainloop的同步在gstreamer pipeline中,mainloop在執(zhí)行了g_main_loop_quit()
之后,mainloop就會(huì)退出,所以需要對(duì)mainloop線程進(jìn)行同步,釋放thread資源。
定義GCond和GMutex:
GCond main_loop_cond;
GMutex main_loop_mutex;
g_mutex_init(&main_loop_mutex);
g_cond_init(&main_loop_cond);
如下,在g_main_loop_run()之后,lock之后修改main_loop_,broadcast之后然后釋放鎖:
g_main_loop_run(player->main_loop_);
g_mutex_lock(&player->main_loop_mutex);
g_main_context_unref(player->context_);
g_main_loop_unref(player->main_loop_);
player->context_ = nullptr;
player->main_loop_ = nullptr;
g_cond_broadcast(&player->main_loop_cond);
g_mutex_unlock(&player->main_loop_mutex);
在主線程,等待main_loop_的狀態(tài)變化:
gint64 end_time = g_get_monotonic_time () + 10 * G_TIME_SPAN_MILLISECOND;
g_mutex_lock(&main_loop_mutex);
while (main_loop_) {g_cond_wait_until(&main_loop_cond, &main_loop_mutex, end_time);
}
g_mutex_unlock(&main_loop_mutex);
g_thread_unref(thread_);
thread_ = nullptr;
或者是g_cond_wait,不帶超時(shí):
g_mutex_lock(&main_loop_mutex);
while (main_loop_) {g_cond_wait(&main_loop_cond, &main_loop_mutex);
}
g_mutex_unlock(&main_loop_mutex);
g_thread_unref(thread_);
thread_ = nullptr;
std::condition_variable::wait
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機(jī)房具備T級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級(jí)服務(wù)器適合批量采購(gòu),新人活動(dòng)首月15元起,快前往官網(wǎng)查看詳情吧