关闭在线程

时间:2015-11-09 00:34:11

标签: c++ multithreading pthreads gstreamer rtsp

我编写了一个在线程上创建RTSP服务器的程序。我认为通过简单地退出运行RTSP服务器的循环(即g_main_loop_quit(loop)),服务器将自行关闭并终止任何现有连接,但看起来并非如此。

我使用VLC播放器预览RTSP流,我注意到当服务器线程退出时(当main仍在运行时),VLC播放器仍然能够从服务器接收传输。如果我关闭播放器,我将无法再次连接到服务器。我不能保持服务器的活动状态,是什么“不解放”或“解放”?

#include <gst/gst.h>
#include <gst/rtsp-server/rtsp-server.h>
#include <stdlib.h>
#include <string>
#include <pthread.h>
#include <iostream>

using namespace std;

int thread_running = 1;

struct ThreadArgs {
    GMainLoop *loop;
};

void *ServerThreadFunction(void *args) {
    g_print("Starting server.\n");

    ThreadArgs *ta = (ThreadArgs *)args;    
    GstRTSPServer *server;
    GstRTSPMediaFactory *factory;
    GstRTSPMountPoints *mounts;

    gst_init(NULL, NULL);

    server = gst_rtsp_server_new();
    gst_rtsp_server_attach(server, NULL);

    factory = gst_rtsp_media_factory_new();
    gst_rtsp_media_factory_set_launch(factory, "( videotestsrc ! x264enc ! rtph264pay pt=96 name=pay0 )");

    mounts = gst_rtsp_server_get_mount_points(server);
    gst_rtsp_mount_points_add_factory(mounts, "/test", factory);
    g_object_unref(mounts);

    g_main_loop_run(ta->loop);

    g_object_unref(server);
    g_print("Terminating server.\n");
    thread_running = 0;
    pthread_exit(NULL);
}

void *KillServerFunction(void *args) {
    ThreadArgs *ta = (ThreadArgs *)args;
    cout << "Is the loop running? " << g_main_loop_is_running(ta->loop) << endl;
    g_main_loop_quit(ta->loop);
    pthread_exit(NULL);
}

int main (int argc, char *argv[]) {
    ThreadArgs *ta = new ThreadArgs;
    ta->loop = g_main_loop_new(NULL, FALSE);

    pthread_t server_thread;
    int rc = pthread_create(&server_thread, NULL, ServerThreadFunction, (void *)ta);

    // Start VLC player here e.g. vlc rtsp://127.0.0.1/test

    sleep(1);
    cout << "Killing server in 3" << endl;
    sleep(1);
    cout << "Killing server in 2" << endl;
    sleep(1);
    cout << "Killing server in 1" << endl;
    sleep(1);

    pthread_t kill_server_thread;
    pthread_create(&kill_server_thread, NULL, KillServerFunction, (void *)ta);

    while (thread_running == 1) {}
    cout << "Program continues to run but stream is still viewable on VLC player..." << endl;
    sleep(100);

    return 0;
}

1 个答案:

答案 0 :(得分:0)

请尝试以下:

需要调用 g_source_remove();

创建服务器:

if ((gst_server_id=gst_rtsp_server_attach (gst_server, NULL)) == 0)
    goto failed;

停止服务器:

 g_source_remove (gst_server_id);

此外,来自gstreamer-rtsp-server docs

  

请注意,如果上下文不是返回的默认主要上下文   g_main_context_default()(或NULL),不能使用g_source_remove()   摧毁源头。在这种情况下,建议使用   gst_rtsp_server_create_source()并手动将其附加到上下文。

相关问题