2012-02-06 80 views
1

比方说,我有这样的创建ç线程

##### 
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串入 - >这里< - 使主要创建两个线程指向两个不同的线程原型?

我想这样做,因为我想创建一个用于创建不同类型的线,这取决于我想要做一个程序,并选择从文本文件(排序的配置文件)

任何建议?

回答

3

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

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); 
0

一个更好的方法是创建一个默认的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); 
}