我从线程开始,我在解决这个问题时遇到了一些问题:
这个程序产生一个有序的数字序列,第二个任务读取它们并将它们打印在屏幕上。我如何修复它以按要求工作?
预期输出:
Consumed item: 1
Consumed item: 2
Consumed item: 3
Consumed item: 4
Consumed item: 5
Consumed item: 6
实际输出:
Consumed item: 1
Consumed item: 4
Consumed item: 7
Consumed item: 10
Consumed item: 11
Consumed item: 14
该程序:
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#define NBUFFERS 2
int item, in=0, out=0;
int buffer[NBUFFERS];
int stop =0;
void *ProducerTask(void *data) //This is the producer task
{
int nextp = 0;
struct timespec mytime;
mytime.tv_sec = 0;
mytime.tv_nsec = 200000000;
while (!stop) {
nanosleep(&mytime, NULL);
nextp++;
buffer[in] = nextp; /* produce a new item */
in = (in + 1) % NBUFFERS;
}
pthread_exit(0);
}
void *ConsumerTask(void *data)
{
int nextc;
struct timespec mytime;
mytime.tv_sec = 0;
mytime.tv_nsec = 500000000;
while (!stop) {
nanosleep(&mytime, NULL);
nextc = buffer[out]; /* consume a item */
out = (out + 1) % NBUFFERS;
printf("Consumed item: %d\n", nextc);
}
pthread_exit(0);
}
void *MonitorTask (void *data) //This is the monitor task
{
getchar();
stop = 1;
pthread_exit(0);
}
void main(void)
{
pthread_t task1;
pthread_t task2;
pthread_t task3;
pthread_create (&task1, NULL, ProducerTask, NULL);
pthread_create (&task2, NULL, ConsumerTask, NULL);
pthread_create (&task3, NULL, MonitorTask, NULL);
pthread_join(task1,NULL);
pthread_join(task2,NULL);
pthread_join(task3,NULL);
printf("Main program exiting.\n");
}