23,128
社区成员
发帖
与我相关
我的任务
分享
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#define MAXNITEMS 1000000
#define MAXNTHREADS 5
int nitems;
struct {
pthread_mutex_t mutex;
int buff[MAXNTHREADS];
int nput;
int nval;
} shared = {
PTHREAD_MUTEX_INITIALIZER
};
void *producer(void *arg)
{
while(1) {
pthread_mutex_lock(&shared.mutex);
if(shared.nput >= nitems) {
pthread_mutex_unlock(&shared.mutex);
return NULL;
}
shared.buff[shared.nput] = shared.nval;
shared.nput++;
shared.nval++;
pthread_mutex_unlock(&shared.mutex);
*((int *)arg) += 1;
}
}
void *consumer(void *arg)
{
int i;
for(i = 0; i < nitems; i++) {
if(shared.buff[i] != i) {
printf("buff[%d] = %d\n", i, shared.buff[i]);
}
}
return NULL;
}
int main(void)
{
int i, nthreads, count[MAXNTHREADS];
pthread_t tid_producer[MAXNTHREADS], tid_consumer;
nitems = MAXNITEMS;
nthreads = MAXNTHREADS;
//pthread_setconcurrency(nthreads + 1);
for(i = 0; i < nthreads; i++) {
count[i] = 0;
pthread_create(&tid_producer[i], NULL, producer, &count[i]);
}
for(i = 0; i < nthreads; i++) {
pthread_join(tid_producer[i], NULL);
printf("count[%d] = %d\n", i, count[i]);
}
pthread_create(&tid_consumer, NULL, consumer, NULL);
pthread_join(tid_consumer, NULL);
exit(0);
}
# SYNCHRONIZATION ./a.out
count[0] = 0
count[1] = 0
count[2] = 0
count[3] = 0
count[4] = 9
buff[5] = 9
buff[6] = 9
# SYNCHRONIZATION ./a.out
count[0] = 9
count[1] = 0
count[2] = 0
count[3] = 0
count[4] = 0
buff[5] = 9
buff[6] = 9