所以我正在研究这个作为生产者-消费者代码的代码。它完全运行在程序中,它实际上从未在临界区执行任何操作,因为它从未真正从睡眠中醒来!我在各处添加了打印语句,试图找出代码在哪里执行,它进入了生产者和消费者函数,但在 sleep() 函数之后从不进入它的任何部分。
这是我的主要内容:
/* 1. Get command line arguments argv[1], argv[2], argv[3] */
/* n1=arg[2], n2=arg[3]
/* 2. Initialize buffer, mutex, semaphores, and other global vars */
/*create the mutex lock */
/* create the semaphore and initialize it to 3 */
/*creating full semaphore and initializing it to 0 */
/*** critical section ***/
/* get the default attribute */
pthread_attr_init(&attr);
/* 3. Create producer thread(s) */
while (count < n1)
{
pthread_t tid;
/* create a new thread */
pthread_create(&tid, &attr, producer, NULL);
count++;
}
printf("OUTSIDE OF PRODUCER CREATION\n");
/* 4. Create consumer thread(s) */
count = 0;
while(count < n2)
{
pthread_t tid2;
/* create a new thread */
pthread_create(&tid2, &attr, consumer, NULL);
count++;
}
printf("after the crit section \n");
/* 5. Sleep */
/* 6. Realease resources, e.g destroy mutex and semaphores */
我已经包含了大部分我知道我遇到问题的代码,其余的是注释。这是我的制片人的代码。消费者基本相同:
void *producer(void *param) {
buffer_item rand;
unsigned int *seed;
seed = (unsigned int *)malloc(sizeof(unsigned int));
*seed = 10;
while (1) {
printf("Inside producer function\n");
/* Sleep for a random period of time */
r = (rand_r(seed))/divide;
sleep(r);
printf("producer slept\n");
//wait(empty)
//wait(mutex)
printf("producer locked mutex\n");
//crit section - add item to buffer
/*Generate a random number */
/*insert random number*/
printf("producer inserted item \n");
if (resp < 0)
printf("Producer error condition\n"); //Report error condition
//signal mutex
//signal empty
}
}
所以当我运行 a.out 4 4 4 时,我得到这个作为我的输出:
Inside producer function
Inside producer function
Inside producer function
OUTSIDE OF PRODUCER CREATION
Inside producer function
inside consumer function
inside consumer function
inside consumer function
after the crit section
inside consumer function
我不确定事情看起来像乱序是否正常......它正在执行 4 次,但你可以看到是否永远不会点击在我的睡眠功能之后发生的打印语句(对于生产者和消费者)
这是作业,所以我只是在寻找更多的方向......