简体   繁体   English

在C中使用Pthread库

[英]Using Pthread library in C

I have this code: 我有以下代码:

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

Before adding p(&full) in consumer function, this code was working fine, randomly selecting one out of two functions every time; 在使用者函数中添加p(&full)之前,此代码可以正常工作,每次都随机从两个函数中选择一个。 but after adding p(&full) in consumer() function, every time it is executing producer() function. 但是在consumer()函数中添加p(&full)之后,每次执行producer()函数时。 I don't understand the reason for this. 我不明白原因。

Can someone please help me,and suggest possible solution for this problem? 有人可以帮助我,并建议解决此问题的方法吗? I want that first time producer function should execute. 我希望第一次执行生产者功能。

Inter-thread synchronisation via shared variables is almost certainly a bad idea, but even so the shared variables should at least be declared volatile . 通过共享变量进行线程间同步几乎肯定不是一个好主意,但是即使如此,共享变量也至少应声明为volatile

Consider using real synchronisation primitives such as semaphores or real Pthreads mutexes . 考虑使用真实的同步原语,例如semaphores真实的 Pthreads互斥体

Your use of the term mutex here is incorrect; 您在此处使用mutex一词不正确; it is not a mutex. 它不是互斥体。 A mutex should be locked and released in the same thread and is intended to prevent other threads accessing a resource. 互斥锁应被锁定并在同一线程中释放,并且旨在防止其他线程访问资源。 If that is not the behaviour hat you want then a mutex is the wrong primitive - perhaps you need a semaphore rather than a mutex. 如果那不是您想要的行为帽,那么互斥体就是错误的原语-也许您需要信号量而不是互斥体。

The code is broken in too many ways to understand what is going on. 代码以太多方式被破坏,无法理解正在发生的事情。 These two issues pop to mind. 这两个问题浮现在脑海。

  1. i-- and i++ are not atomic operations, so the neither mutex or full has the values you think they do. i--和i ++不是原子操作,因此互斥体或full都不具有您认为它们具有的值。

  2. You are creating 20 threads but only joining on the last two. 您正在创建20个线程,但仅在最后两个线程上加入。

  3. You have no memory barriers in the code so that order of how changes to memory in an SMP system is practically undefined. 您的代码中没有内存障碍,因此实际上未定义SMP系统中内存更改的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM