在循环中创建和连接pthread

时间:2015-04-12 20:27:29

标签: c pthreads

通过循环创建线程我遇到了一个奇怪的问题。我有一个线程数组,用户可以指定从1到25的线程数。我遇到的一个特定问题是在循环并加入线程数组中的单独线程时遇到seg错误。我调试它,看到数组中的线程值偶尔散布。例如,如果用户指定了9个线程,并且该数组总共包含25个可能的线程,那么该数组将如下所示:

{0, 0, 12332342, 0, 0, 123212313, ...}

基本上,填充的索引不是如预期的那样从索引0到9,而是遍布整个数组。

我的代码有点乱,所以我只包含相关部分,如果需要更多上下文,请告诉我:

int max_chld_threads = p_args->num_threads - 1;
int chld_threads_delay = p_args->cons_chld_delay;
pthread_t chld_threads[25];
consargs chld_c_args[25];
char chld_name[2] = {'B', 0};
int thd_cnt = 0;
size_t max_char = MAX_CHAR_PER_LINE - 1;
char term_sentinel[] = "@$%#";
int i;
char *cur_file;
char *line;
void *retval;

if ((line = (char *) malloc(max_char * sizeof(char))) == NULL) {
    perror("Malloc failed");
    exit(1);
}

//Opening files in file array
for (i = 0; i < num_files; i++) {
    cur_file = *(file_path_lst + i);
    if ((fp = fopen(cur_file, "r")) == NULL) {
        perror("Cannot open");
        continue;
    }
    while (getline(&line, &max_char, fp) != -1) {
        put (&buffer, line);

        //Creates new child thread if buffer is full
        if (thd_cnt < max_chld_threads && buffer.full == 1) {

            //Copies the argument which contains a thread's name
            strncpy(chld_c_args[thd_cnt].name, chld_name, sizeof(chld_c_args));
            chld_c_args[thd_cnt].delay = chld_threads_delay;

            if (pthread_create (&chld_threads[thd_cnt], NULL, consumer,
                                (void *) &chld_c_args[thd_cnt]) != 0) {
                perror("Child consumer thread creation failed");
                continue;
            }

            //Increment the letter for next child thread
            chld_name[0]++;
            thd_cnt++;
        }
    }
    fclose(fp);
}
put (&buffer, term_sentinel);
/* Join here */
for (i = 0; i < thd_cnt; i++) { //SEGFAULTS here
    pthread_join (chld_threads[i], &retval);
}

consargs:

struct consargs
{
    int delay;
    char name[2];
};

1 个答案:

答案 0 :(得分:1)

不确定这是否导致您的特定问题,但您可能在此行中有缓冲区溢出:

strncpy(chld_c_args[thd_cnt].name, chld_name, sizeof(chld_c_args));

应该是:

strncpy(chld_c_args[thd_cnt].name, chld_name, 
        sizeof(chld_c_args[thd_cnt].name));

strncpy会用零填充dest。所以你可能会覆盖thd_cnt(以及其他变量)。