我从线程开始,在解决这个问题时遇到了一些问题:
该程序生成一个有序的数字序列,第二个任务读取它们并将它们打印在屏幕上。我该如何修复它才能按要求工作?
预期输出:
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");
}
最佳答案
int buffer[NBUFFERS];
int stop =0;
是全局的并且从多个线程访问,它们没有任何 synchronization 。
race condition 接下来的问题即使不是问题,也是问题。
加粗的内联链接至少应该让您在做错的事情上领先一步。
关于c - Pthread C 同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10222826/