线程中的全局变量指针

时间:2014-01-02 18:27:44

标签: c multithreading pointers global

我不能在线程中使用我的全局变量指针buffer1。给我分段错误。为什么?谢谢。

# include <stdio.h>
# include <stdlib.h>
# include <pthread.h>
# include <malloc.h>
# include <semaphore.h>

int **buffer1;


int **crear_buffer(int tamano) {

    int i;
    int **matriz = (int **)malloc(sizeof(int *) * tamano);

    for (i = 0; i < tamano; i++) {
        matriz[i] = (int *)malloc(sizeof(int) * 2);
    }

    return matriz;
}

void *productor(void *arg){

    int num_pares= *((int *) arg);

    int i=0;
    int cont=0;

    while(cont<num_pares){

    int primero=5;
    int segundo=8;

    if (primero<=segundo){
        buffer1[i][0]=primero;
        buffer1[i][1]=segundo;
    }
    else{
        buffer1[i][0]=segundo;
        buffer1[i][1]=primero;

    }

    i=(i+1)%tamano_buffer1;
    cont++;

    }

    pthread_exit(NULL);

}


int main(int argc, char *argv[]){

    sscanf(argv[1], "%d", &tamano_buffer1);
    sscanf(argv[2], "%d", &N);

    int **buffer1=crear_buffer(tamano_buffer1);

    pthread_t tid_productor;

    pthread_create(&tid_productor, NULL, productor,(void *) &N);

    pthread_join(tid_productor, NULL); 
    return 0;
}

1 个答案:

答案 0 :(得分:2)

因为您从未分配过它:

这是一个名为buffer1的新局部变量:

int **buffer1=crear_buffer(tamano_buffer1);

这将分配给您现有的全局变量:

buffer1=crear_buffer(tamano_buffer1);