【问题标题】:Pthread C syncronizationPthread C 同步
【发布时间】:2012-04-30 15:47:00
【问题描述】:

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

这个程序产生一个有序的数字序列,第二个任务读取它们并将它们打印在屏幕上。如何根据需要修复它以使其正常工作?

预期输出:

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");
}

【问题讨论】:

  • “修复这个程序”绝对不是描述问题的好方法。您需要正确地查明并描述您的问题以获得良好的响应
  • 预期结果(或输出)是什么,实际结果是什么?换句话说,你的问题是什么?
  • 输出:消耗品:1 消耗品:4 消耗品:7 消耗品:10 消耗品:11 消耗品:14
  • 并且应该是:消耗品:1 消耗品:2 消耗品:3 消耗品:4 消耗品:5 消耗品:6
  • 你为什么期望这个顺序的o/p?线程被允许以任何顺序运行,因为它们被安排,你没有提供任何同步,使它们遵循你想要的顺序。

标签: c linux multithreading pthreads


【解决方案1】:
int buffer[NBUFFERS];
int stop =0; 

是全局的,可以从多个线程访问,它们没有任何 synchronization
如果不是 问题,那么接下来的 race condition一个 问题。

加粗的内联链接应该至少让您在做错的事情上领先一步。

【讨论】:

【解决方案2】:

共享资源至少需要锁定和传递数据通常通过条件变量通过线程通信解决,请参阅this example(C++,但它表明了我的观点)。

编辑:在这种情况下,奇怪的输出是由于您使用了一个小缓冲区以及一个比生产者慢的消费者。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2013-06-04
    相关资源
    最近更新 更多