0
我已经实施了一个解决方案,使用pthreads和信号量在C中的生产者/消费者问题。缓慢的pthread消费者
我的主线程是生产者,我启动N个消费者线程。
我的代码是:
typedef struct
{
int buf[BUFSIZE]; /* shared var */
int in; /* buf[in%BUFSIZE] is the first empty slot */
int out; /* buf[out%BUFSIZE] is the first full slot */
sem_t full; /* keep track of the number of full spots */
sem_t empty; /* keep track of the number of empty spots */
pthread_mutex_t mutex; /* enforce mutual exclusion to shared data */
} CONSUMER_STRUCT;
CONSUMER_STRUCT shared;
这是我的每一个消费者线程的代码:
void *Consumer(void *arg)
{
int fd, workerID, i, hit=0;
workerID = *(int *)arg;
for (;;) {
sem_wait(&shared.full);
pthread_mutex_lock(&shared.mutex);
fd = shared.buf[shared.out];
printf("\n[C%d] Consumed. I got %d ...Valor do buffer: %d na posição %d\n\n\n", workerID, fd, shared.buf[shared.out], shared.out);
ftp(fd, hit);
shared.buf[shared.out] = 0;
shared.out = (shared.out+1)%BUFSIZE;
fflush(stdout);
printf("\n\n\n\nEstado do buffer:\n\n\n\n");
for (i = 0; i < BUFSIZE; i++) {
//printf("%d ", shared.buf[i]);
}
/* Release the buffer */
pthread_mutex_unlock(&shared.mutex);
/* Increment the number of full slots */
sem_post(&shared.empty);
hit++;
}
return NULL;
}
这是我的生产者线程代码:
item = socketfd;
sem_wait(&shared.empty);
pthread_mutex_lock(&shared.mutex);
shared.buf[shared.in] = item;
shared.in = (shared.in + 1) % BUFSIZE;
fflush(stdout);
pthread_mutex_unlock(&shared.mutex);
sem_post(&shared.full);
一切工作正常,但服务22个文件需要大约20秒,而每个请求创建一个线程大约需要2个秒!这似乎是一次执行一个线程,我想要“同时”执行所有的线程。
我在执行方法中做错了什么?
您的消费者在整个操作过程中都持有互斥锁。您正在运行单线程同步开销。 – EOF
我明白你的意思了!什么应该是解决这个问题的正确方法? – rafaelcpalmeida
让我们暂时假设Consumer()中的'ftp()'支配着消费者的执行时间。此外,我们假设'ftp()'是线程安全的。然后,你可以在'pthread_mutex_unlock()'下面移动'ftp()'并且实际同时执行。 – EOF