【问题标题】:How to pass GLib.Thread arguments如何传递 GLib.Thread 参数
【发布时间】:2018-01-08 19:14:43
【问题描述】:

我发现的典型 GLib.Thread 示例是一种类型:

new Thread<void*>(null,() => { return null; };

这在不向线程传递参数时效果很好。

GLib.Thread 文档展示了一个使用类实例提供线程数据的示例。

// Start a thread:
MyThread my_thread = new MyThread (10);
Thread<int> thread = new Thread<int>.try ("My fst. thread", my_thread.run);

这是向线程传递参数的唯一方法吗?文档还说:

新线程通过使用参数数据调用 func 开始。数据:
提供给新线程的参数。

参数数据在哪里指定以及如何在线程中访问它?

例如,想象一下这个回调签名:

private string cbThreadSample(int id,string msg, Socket client_socket){
   //...do stuff
   return "good job";
   }

我的使用想法是这样的:

new GLib.Thread<string>("my thread sample",this.cbThreadSample,id,msg, client_socket);

显然这不会编译。使用此回调签名创建线程的正确方法是什么?

【问题讨论】:

    标签: vala


    【解决方案1】:

    数据参数是您传递给线程的委托的一部分。

    如果你这样做:

    new GLib.Thread<string>("my thread sample",
      () => this.cbThreadSample(id,msg, client_socket));
    

    在底层 C 代码中,这将被翻译成这样的:

    struct lambda0__data {
      WhateverClass *self;
      int id;
      gchar *msg;
      GSocket client_socket;
    };
    
    void *lambda0__func(lambda0__data *context) {
       whatever_class_cbThreadSample(context->self,
         context->id, context->msg,
         context->client_socket));
        return NULL;
    }
    
    ...
    lambda0__data *thread_data = g_new0(lambda0__data);
    thread_data->self = self;
    thread_data->id = id;
    thread_data->msg = gstrdup(msg);
    thread_data->client_socket = g_object_ref(socket);
    g_thread_try_new("my thread sample", lambda0__func, thread_data);
    

    传递的数据参数与委托(lambda 或方法引用)相关联。在使用子类MyThread的情况下,MyThread的实例将作为数据参数传递。

    这不能直接访问。它作为 lambda 的捕获或实例的 this 隐式传递。

    另外,如果您实际上将它用于请求处理程序,您可能希望使用ThreadPool

    【讨论】:

    • 感谢您的详细解释!
    猜你喜欢
    • 1970-01-01
    • 2016-09-24
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    相关资源
    最近更新 更多