c - Pthread C 同步

标签 c linux multithreading pthreads

我从线程开始,在解决这个问题时遇到了一些问题:

该程序生成一个有序的数字序列,第二个任务读取它们并将它们打印在屏幕上。我该如何修复它才能按要求工作?

预期输出:

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/

相关文章:

c - 指向字符串的指针

c - 简单的 ADD/ADC ARM 组件失败

c++ - 如何在没有库的情况下对 double 组进行有效排序?

Linux 操作系统类的内容

c++ - 无法使用 C++11 线程类在单独的线程中调用类成员函数

c - 将 int 数组分配给 int 指针

linux - 将文件移动到Linux中的子目录

linux - tcpdump 单行​​输出

c# - 使用 Azure WebJobs 调用静态方法

c++ - 如果 ANSI C++ 不支持多线程,非托管 C++ 应用程序如何实现多线程?