gpt4 book ai didi

c - pthread_create segfault(缓冲读取器示例)

转载 作者:行者123 更新时间:2023-11-30 18:37:48 25 4
gpt4 key购买 nike

我已经为我的操作系统类的缓冲读取器问题编写了一个简单的解决方案,但是在几个成功的生产者线程之后,我遇到了段错误。输出、bt 和代码如下:

输出:

Producer 1 exiting
Producer 2 exiting
Producer 3 exiting
Segmentation fault (core dumped)

线程 BT(使用 GDB 线程应用所有位置):

Thread 2 (Thread 0x7ffff77f6700 (LWP 8310)):
#0 0x0000000000000000 in ?? ()
#1 0x00007ffff7bc4182 in start_thread (arg=0x7ffff77f6700)
at pthread_create.c:312
#2 0x00007ffff78f147d in clone ()
at ../sysdeps/unix/sysv/linux/x86_64/clone.S:111

Thread 1 (Thread 0x7ffff7fd3740 (LWP 8299)):
#0 0x00007ffff78eba27 in mprotect () at ../sysdeps/unix/syscall-template.S:81
#1 0x00007ffff7bc4f21 in allocate_stack (stack=<synthetic pointer>,
pdp=<synthetic pointer>, attr=0x7fffffffde20) at allocatestack.c:650
#2 __pthread_create_2_1 (newthread=0x6021e0, attr=<optimized out>,
start_routine=0x0, arg=0x0) at pthread_create.c:500
#3 0x00000000004009cf in start_producer () at 6-2.c:75
#4 0x00000000004007e9 in main () at 6-2.c:29

代码:

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

void init();
void start_producer();
void start_consumer();
void *produce();
void *comsume();


int buffer_count;
int max_buffers;
int producer_count;
sem_t *mutex;
sem_t *full;
sem_t *empty;

int main() {
init();

int i = 0;

for(i = 0; i < 3; i++) {
start_producer();
}

for(i = 0; i < 3; i++) {
start_consumer();
}
return 0;
}

void init() {
buffer_count = 0;
max_buffers = 3;
producer_count = 0;
mutex = malloc(sizeof(sem_t));
full = malloc(sizeof(sem_t));
empty = malloc(sizeof(sem_t));

sem_init(mutex, 0, 1);
sem_init(full, 0, 0);
sem_init(empty, 0, max_buffers);
}

void *produce() {
sem_wait(empty);
sem_wait(mutex);
producer_count++;
printf("Producer %d exiting\n", producer_count);
sem_post(full);
sem_post(mutex);
return 0;
}

void *consume() {
sem_wait(full);
sem_wait(mutex);
printf("Consuming produced value: %d\n", producer_count);
producer_count--;
sem_post(empty);
sem_post(full);
return 0;
}

void start_producer() {
pthread_t *thread = malloc(sizeof(pthread_t));
if(pthread_create(thread, NULL, produce(), NULL) != 0)
printf("\tError creating producer thread.\n");
}

void start_consumer() {
pthread_t *thread = malloc(sizeof(pthread_t));
if(pthread_create(thread, NULL, consume(), NULL) != 0)
printf("\tError creating consumer thread.\n");
}

我知道这可能是一个新问题。我很难调试这个。预先感谢您的帮助。

最佳答案

您将NULL传递给pthread_create的第三个参数,这很有可能导致段错误。

尝试这些行

if(pthread_create(thread, NULL, produce, NULL) != 0)
if(pthread_create(thread, NULL, consume, NULL) != 0)

而不是

if(pthread_create(thread, NULL, produce(), NULL) != 0)
if(pthread_create(thread, NULL, consume(), NULL) != 0)

(不要调用productconsume,而是传递它们的指针)

关于c - pthread_create segfault(缓冲读取器示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35859585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com