【发布时间】:2016-07-06 23:46:06
【问题描述】:
为一个班级处理生产者和消费者问题,但在最后润色时遇到了麻烦。我遇到的问题是我认为我的互斥锁没有将我的线程锁定在函数之外。例如,如果我运行程序并将参数传递给它 2 4 4 7,它将打印 8 个 7,然后 2 秒后它将打印 8 个 8,然后是 8 个 9,依此类推。我曾尝试使用 trylock 并在信号量周围移动,但无济于事。当没有任何线程被锁定时,我是否遗漏了什么?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
typedef int buffer_item;
#define BUFFER_SIZE 5
#define TRUE 1
buffer_item START_NUMBER;
int counter;
int insert_item(buffer_item item);
int remove_item(buffer_item *item);
buffer_item buffer[BUFFER_SIZE];
void* producer(void *ptr);
void* consumer(void *ptr);
pthread_cond_t condc, condp;
pthread_mutex_t mutex;
int sleepTime, producerThreads, consumerThreads,a;
pthread_attr_t attr;
sem_t full, empty;
int insert_item(buffer_item item)
{
if(counter < BUFFER_SIZE) {
buffer[counter] = item;
counter++;
return 0;
}
else {
return -1;
}
}
int remove_item(buffer_item *item)
{
if(counter > 0) {
*item = buffer[(counter-1)];
counter--;
return 0;
}
else {
return -1;
}
}
void* producer(void *ptr) {
buffer_item item;
item = START_NUMBER;
while(TRUE) {
sleep(sleepTime);
sem_wait(&empty);
pthread_mutex_lock(&mutex);
if(insert_item(item)) {
fprintf(stderr, "error \n");
}
else {
printf("producer%u produced %d\n", (unsigned int)pthread_self(),item);
item++;
}
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void* consumer(void *ptr) {
buffer_item item;
while(TRUE) {
sleep(sleepTime);
sem_wait(&full);
pthread_mutex_lock(&mutex);
if(remove_item(&item)) {
fprintf(stderr, "error \n");
}
else {
printf("consumer%u consumed %d\n", (unsigned int)pthread_self(),item);
}
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
void initializeData() {
pthread_mutex_init(&mutex, NULL);
sem_init(&full, 0, 0);
sem_init(&empty, 0, BUFFER_SIZE);
pthread_attr_init(&attr);
counter = 0;
}
int main(int argc, char **argv) {
sleepTime = atoi(argv[1]);
producerThreads = atoi(argv[2]);
consumerThreads = atoi(argv[3]);
START_NUMBER = atoi(argv[4]);
initializeData();
pthread_t pro, con;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&condc, NULL);
pthread_cond_init(&condp, NULL);
for(a=0; a< consumerThreads;a++)
pthread_create(&con, NULL, consumer, NULL);
for(a=0;a<producerThreads;a++)
pthread_create(&pro, NULL, producer, NULL);
pthread_join(con, NULL);
pthread_join(pro, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
sleep(sleepTime);
}
【问题讨论】:
-
你期待什么输出?
-
啊,我的错误,预期输出是从开始时采用的 4 参数开始递增的数字 producer 12323112 生产了 7 个生产者 12312310 生产了 8 个消费者 1321312 消费了 7 个生产者 ...9 消费者 。 ....消耗了 8`
-
按原样,每个(生产者)线程都以自己的
item变量开始,初始化为START_NUMBER。由于他们每个人都使用并增加自己的本地副本,因此您将获得与生产者一样多的每个数字的副本......每个显示两次,生产时一次,消费时一次 - 因此四个生产者线程八次。 -
抱歉格式不好,我对这个网站几乎是全新的,基本上它会说的是.. 生产了 7 个换行符,生产了 8 个换行符,消耗了 7 个换行符,生产了 9 个换行符,消耗了 8 个换行符。 ...然后无限循环
-
如果你不想重复,也许生产者应该使用全局变量作为计数器,而不是他们自己的本地变量
item。
标签: c mutex semaphore consumer producer