每次尝试运行它时,带有锁的并发链接列表都会引发分段错误(核心转储)

我试图将其插入并发链接列表。当我尝试使用list_insert函数时,我的代码总是给我分段错误(内核已转储),但我不知道为什么。从一个空列表开始,两个线程同时运行,我试图在同一列表中插入100万个随机整数。我已附上我的代码。感谢您的帮助

// basic node structure
typedef struct __node_t {
int key;
struct __node_t *next;
} node_t;


//basic list structure (one used per list)
    typedef struct __list_t {
    node_t *head;
    pthread_mutex_t lock;
} list_t;`

void List_Init(list_t *L) {
L->head == NULL;
pthread_mutex_init(&L->lock, NULL);
}

void List_Insert(list_t *L, int key) {
// synchronization not neded
node_t *new = malloc(sizeof(node_t));
if (new == NULL){
    perror("malloc");
    return;
}
new->key = key;

// just lock cricical section
pthread_mutex_lock(&L->lock);
new->next = L->head;
L->head = new;
pthread_mutex_unlock(&L->lock);
}

主功能

//main function 
int main(int argc, char** argv){

// create random number
srand(time(0));

//create list
list_t *the_list;
List_Init(the_list);

struct timeval start, stop;

// start of timer
gettimeofday(&start, NULL);

printf(" %d ", rand());
List_Insert(the_list, 1);

//stop timer
gettimeofday(&stop, NULL);

//get time passed
double time;

time = (stop.tv_sec - start.tv_sec) * 1e6;
time = (time + (stop.tv_usec - start.tv_usec)) * 1e-6;

printf("Time Passed: %f\n", time);

return 0;
评论