【问题标题】:creating C threads from text file从文本文件创建 C 线程
【发布时间】:2012-02-28 08:41:50
【问题描述】:

假设我有一个这样组成的文本文件

#####
typeofthread1

#####
typeofthread2

等等……

在我的主目录中,我想读取该文件,获取字符串 typeofthread1、typeofthread2 并使用创建不同的线程

pthread_t threads[NUM_THREADS];
for (i=0;i<NUM_THREADS;i++)
    pthread_create(&threads[i], NULL, -> HERE <- , void * arg);

如何将刚刚读取的 typeofthread1typeofthread2 字符串放入 -> HERE

我想这样做是因为我想创建一个程序来创建不同类型的线程,这取决于我想要做什么,并从文本文件(某种配置文件)中选择它

有什么建议吗?

【问题讨论】:

    标签: c multithreading file dynamic


    【解决方案1】:

    将字符串名称映射到函数指针。

    void * thread_type_1 ( void * );
    void * thread_type_2 ( void * );
    
    typedef  void * (*start_routine_t)(void *);
    
    typedef struct mapping_t {
    
         const char * name;
         start_routine_t function;
    
    } mapping_t;
    
    const mapping_t mappings[] = {
        {"thread-type-1", &thread_type_1},
        {"thread-type-2", &thread_type_2},
    };
    const size_t mapping_count =
        sizeof(mappings)/sizeof(mappings[0]);
    

    要选择正确的线程函数,循环mappings 中的项目并在名称匹配时获取函数。

    start_routine_t get_start_routine ( const char * name )
    {
        size_t i;
        for ( i=0; i < mapping_count; ++i )
        {
            if (strcmp(name,mappings[i].name) == 0) {
                return mappings[i].function;
            }
        }
        return NULL;
    }
    

    在您启动线程的任何地方,您都可以将其用作:

    start_routine_t start_routine;
    
    /* find start routine matching token from file. */
    start_routine = get_start_routine(name);
    if (start_routine == NULL) {
        /* invalid type name, handle error. */
    }
    
    /* launch thread of the appropriate type. */
    pthread_create(&threads[i], NULL, start_routine, (void*)arg);
    

    【讨论】:

      【解决方案2】:

      更好的方法是创建一个默认的thread_dispatch 函数,您可以使用该函数启动所有pthreads。这个分派函数将包含一个包含void* 的结构到一个包含线程特定数据的结构,以及一个指定要运行的线程函数类型的字符串。然后,您可以使用将字符串映射到代码模块中创建的函数指针类型的查找表,找到适当的函数指针,并将线程特定的数据传递给该函数。所以这看起来像下面这样:

      typedef struct dispatch_data
      {
          char function_type[MAX_FUNCTION_LENGTH];
          void* thread_specific_data;
      } dispatch_data;
      
      void* thread_dispatch(void* arg)
      {
          dispatch_data* data = (dispatch_data*)arg;
      
          //... do look-up of function_pointer based on data->function_type string
      
          return function_pointer(data->thread_specific_data);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-03
        • 2017-03-06
        • 1970-01-01
        • 2023-04-02
        • 2021-08-17
        • 2020-04-16
        • 2020-01-19
        • 2016-10-15
        相关资源
        最近更新 更多