在做计蒜客的题目的时候,被难住了,做不出来就不能学习后面的内容,大家帮帮我,贡献下c语言代码把
是操作系统与系统编程关于生产者与消费者#include<stdlib.h>#include<pthread.h>structstack_entry{void*data;s...
是操作系统与系统编程关于生产者与消费者#include <stdlib.h>#include<pthread.h>struct stack_entry { void *data; struct stack_entry *next;};struct stack { struct stack_entry *head; int capacity; int count; pthread_mutex_t mutex;};struct stack *new_stack(int capacity) { struct stack *my_stack = calloc(1, sizeof(struct stack)); if (my_stack == NULL) { return NULL; } my_stack->head = NULL; my_stack->capacity = capacity; my_stack->count = 0; pthread_mutex_init (&my_stack->mutex,NULL); return my_stack;}int push(struct stack *my_stack, void *data) { if (pthread_mutex_lock(&my_stack->mutex) != 0) { return -1;} if (my_stack->count == my_stack->capacity) { return -1; } struct stack_entry *new_entry = calloc(1, sizeof(struct stack_entry)); if (new_entry == NULL) { return -1; } new_entry->data = data; new_entry->next = my_stack->head; my_stack->head = new_entry; my_stack->count += 1; return 0; if (pthread_mutex_unlock(&my_stack->mutex) != 0) { return -1;}}if (pthread_mutex_lock(&my_stack->mutex) != 0) { return (void *)-1;}void *pop(struct stack *my_stack) { if (my_stack->count == 0) { return NULL; } struct stack_entry *top = my_stack->head; my_stack->head = top->next; void *data = top->data; free(top); my_stack->count -= 1; return data; if (pthread_mutex_unlock(&my_stack->mutex) != 0) { return (void *)-1;}}int main() { return 0;}我不知道哪错了,求帮忙
展开
1个回答
展开全部
不是和普通的puah pop差不多嘛 在之前加锁就醒了
追问
不会啊~求具体代码啊!!!!!
追答
#include <stdlib.h>
#include<pthread.h>
struct stack_entry {
void *data;
struct stack_entry *next;
};
struct stack {
struct stack_entry *head;
int capacity;
int count;
pthread_mutex_t mutex;
};
struct stack *new_stack(int capacity) {
struct stack *my_stack = calloc(1, sizeof(struct stack));
if (my_stack == NULL) {return NULL;}
my_stack->head = NULL;
my_stack->capacity = capacity;
my_stack->count = 0;
pthread_mutex_init (&my_stack->mutex,NULL);
return my_stack;
}
int push(struct stack *my_stack, void *data) {
//前面加锁後面释放就行了
if (pthread_mutex_lock(&my_stack->mutex) != 0) {return -1;}
if (my_stack->count == my_stack->capacity) {return -1;}
struct stack_entry *new_entry = calloc(1, sizeof(struct stack_entry));
if (new_entry == NULL) {return -1;}
new_entry->data = data;
new_entry->next = my_stack->head;
my_stack->head = new_entry;
my_stack->count += 1;
if (pthread_mutex_unlock(&my_stack->mutex) != 0) { return -1;}
return 0;
}
void *pop(struct stack *my_stack) {
if (pthread_mutex_lock(&my_stack->mutex) != 0){return (void *)-1;}
if (my_stack->count == 0) {return NULL;}
struct stack_entry *top = my_stack->head;
my_stack->head = top->next;
void *data = top->data;
free(top);
my_stack->count -= 1;
if (pthread_mutex_unlock(&my_stack->mutex) != 0) { return (void *)-1;}
return data; //释放了top没法返回top->data了a。
}
int main() {return 0;}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询