简体   繁体   English

具有多线程的分段错误(ncurses)

[英]Segmentation fault with multithreading (ncurses)

Having the following struct and global var: 具有以下结构和全局变量:

typedef struct Column{
    char * text;
    int size; 
} Column;

Column * screen;

And this thread function: 而这个线程功能:

void * thread_function(void * msg){
    Info *mesg = (Info *)msg;
    int col = mesg->c;

    int count = 0;
    while (count < MAX_ELEM){
        if (rand() % 2){ 
            screen[col].text[count] = ' ';
            screen[col].size++;    
            count++;
        } 
        else{
            screen[col].text[count] = 'a';
            screen[col].size++;    
            count++;
        }
    }
}

In the main function after I join the threads I start printing the content of the screen 在加入线程后的主要功能中,我开始打印screen内容

int row = 42; // num of rows on the screen
while(true){
        int i;
        for (i = 0; i<col; i++){
            int j = screen[i].size - 1; // print only up to already assign value
            int k = 0;
            while (j >= 0 && k < row){
                mvprintw(k,i,"%c",screen[i].text[j]);
                refresh();
                j--;
                k++;
            }
        }
        refresh();
    }

The issue is that some runs execute normally, while others generate a Seg fault err after a few iterations of the while(true) (Note: at least something is always printed). 问题在于,某些运行正常执行,而其他运行则在while(true)的几次迭代后生成Seg错误err(注意:至少总是打印某些内容)。 If I remove mvprintw() from the while(true) the seg fault never occurs. 如果我从while(true)删除mvprintw() ,则绝不会发生seg错误。 What can be the issue? 可能是什么问题?

Ps Please do not post answers which are related to mutex, as this is an assignment and I would prefer to correct the problem I have, rather reimplement the idea especially when it can be performed without mutex. 附言:请不要发表与互斥有关的答案,因为这是一项作业,我希望更正我遇到的问题,而应重新实现该想法,尤其是在无需互斥的情况下执行。

Edits: 编辑:

allocation of global var screen (part of main) 全局var screen分配(主要部分)

screen = malloc(col * sizeof(Column *));
i = 0;
    for (; i<col; i++){
        screen[i].text = malloc(MAX_ELEM * sizeof(char));
        screen[i].size = 0;
    }

Output screen at seg faults: 段故障时的输出屏幕:

                                                              a a             Segmentation fault (core dumped)

Output screen at no seg fault: 无段故障时的输出屏幕:

         a                            a  a              a             a     aa
                        a  a                                        a

Feel that 觉得

screen = malloc(col * sizeof(Column *));

to be 成为

screen = malloc(col * sizeof(Column)); 

because sizeof(Column *) would return only the size of pointer 因为sizeof(Column *)将仅返回指针的大小

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM