可能有人检查我的代码,并告诉我,如果我在正确的轨道上。它好像我有点失去了..如果你看到我的错误,请让我知道他们..生产者/消费者
我想要做的是使用我自己的信号量和GCD解决有界缓冲区。
在此先感谢..
sema.c
void procure(Semaphore *semaphore) {
pthread_mutex_lock(semaphore->mutex1);
while(semaphore->value <= 0)
pthread_cond_wait(&semaphore->condition, semaphore->mutex1);
semaphore->value--;
pthread_mutex_unlock(semaphore->mutex1);
}
void vacate(Semaphore *semaphore) {
pthread_mutex_lock(semaphore->mutex1);
semaphore->value++;
pthread_cond_signal(&semaphore->condition);
pthread_mutex_unlock(semaphore->mutex1);
}
void init (Semaphore *semaphore){
semaphore->value = 1;
pthread_mutex_t myMutex;
semaphore->mutex1 = &myMutex;
pthread_mutex_init(semaphore->mutex1, NULL);
}
void destroy (Semaphore *semaphore) {
pthread_mutex_destroy(semaphore->mutex1);
}
和main.c中
struct variables {
Semaphore *sem;
};
struct variables vars;
void constructer (int *buffer, int *in, int *out) {
init(vars.sem);
}
void deconstructer() {
destroy(vars.sem);
}
int rand_num_gen() {
uint_fast16_t buffer;
int file;
int *rand;
file = open("/dev/random", O_RDONLY);
while(1) {
read(file, &buffer, sizeof(buffer));
printf("16 bit number: %hu\n", buffer);
*rand = (int) buffer;
close(file);
break;
}
return *rand;
}
void put_buffer(int* buffer, int* in, int* out) {
buffer[*in] = rand_num_gen(); // produce
procure(vars.sem); // wait here
*in = (*in + 1) % BUF_SIZE;
vacate(vars.sem);
}
void get_buffer(int* buffer, int* in, int* out) {
int value;
procure(vars.sem);
value = buffer[*out];
vacate(vars.sem);
*out = (*out + 1) % BUF_SIZE;
}
int main (void) {
int *in, *out, *buffer;
constructer(buffer, in, out);
dispatch_queue_t producer, consumer;
producer = dispatch_queue_create("put_buffer", NULL);
consumer = dispatch_queue_create("get_buffer", NULL);
dispatch_async(producer,
^{
int i;
do
{
put_buffer(buffer, in, out);
dispatch_async(consumer,
^{
get_buffer(buffer, in, out);
if (i == RUN_LENGTH) exit(EXIT_SUCCESS);
});
}
while (i < RUN_LENGTH);
});
dispatch_main();
deconstructer();
exit (0);
}
我在这里收到坏访问'buffer [* in] = rand_num_gen();'我该如何解决它? – canaan
这是哪种语言? C没有lambda('^')运算符。 –