【问题标题】:Using Pthread library in C在 C 中使用 Pthread 库
【发布时间】:2016-03-13 01:04:00
【问题描述】:

我有这个代码:

#include<stdio.h>
#include<pthread.h>

int mutex=1,i=0,full=0;

void p(int *s)
{
    while(*s<=0)

    ;

    *s--;
}

void v(int *s)
{
    *s++;
}

void *producer()
{
    p(&mutex);
    printf("Producer is producing\n");
    v(&mutex);
    v(&full);
}

void *consumer()
{
    p(&full);
    p(&mutex);
    printf("Consuming\n");
    v(&mutex);
}

int main()
{
    pthread_t thread1,thread2;
    int k;

    for(k=0;k<10;k++)
    {       
        pthread_create(&thread1,NULL,(void *(*)(void *))producer,NULL);
        pthread_create(&thread2,NULL,(void *(*)(void *))consumer,NULL);
    }

    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);
}

在消费者函数中添加p(&amp;full)之前,这段代码运行良好,每次随机选择两个函数中的一个;但是在consumer()函数中添加p(&amp;full)后,每次执行producer()函数。我不明白这是为什么。

有人可以帮助我,并为这个问题提出可能的解决方案吗?我希望第一次执行生产者功能。

【问题讨论】:

  • *s-- 表示*(s--) 不是(*s)--

标签: c pthreads producer-consumer


【解决方案1】:

代码被破坏的方式太多,无法理解发生了什么。这两个问题浮现在脑海中。

  1. i-- 和 i++ 不是原子操作,因此 mutex 或 full 都没有您认为的值。

  2. 您正在创建 20 个线程,但只加入最后两个线程。

  3. 代码中没有内存屏障,因此在 SMP 系统中更改内存的顺序实际上是未定义的。

【讨论】:

    【解决方案2】:

    通过共享变量进行线程间同步几乎肯定是个坏主意,但即便如此,共享变量至少应该声明为volatile

    考虑使用真正的同步原语,例如 semaphoresreal Pthreads mutexes

    您在这里使用术语mutex 是不正确的;它不是互斥体。互斥锁应在同一线程中锁定和释放,旨在防止其他线程访问资源。如果这不是您想要的行为帽子,那么互斥锁是错误的原语 - 也许您需要一个信号量而不是互斥锁。

    【讨论】:

      猜你喜欢
      • 2011-02-10
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      • 2014-11-27
      • 2019-07-12
      • 2013-01-09
      • 1970-01-01
      相关资源
      最近更新 更多