首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >拉里,莫伊,卷毛互斥

拉里,莫伊,卷毛互斥
EN

Stack Overflow用户
提问于 2016-03-04 14:58:17
回答 1查看 397关注 0票数 0

问题陈述:

“拉里、莫伊和卷毛正在播种。拉里挖洞,然后在每个洞里放一粒种子。卷曲然后填满这个洞。有几个同步限制:

  • 除非至少有一个空洞存在,否则Moe无法播种种子,但是Moe并不关心拉里领先Moe有多远。
  • 卷曲不能填补一个洞,除非至少有一个洞,莫伊已种下种子,但该洞尚未填补。卷毛不在乎莫伊比卷毛跑多远。
  • Curly确实关心拉里不会得到比Curly更多的马克斯·孔。因此,如果有最大的未填补的洞,拉里不得不等待。
  • 只有一个铲子,拉里和居里都需要用它分别挖洞和填洞。

设计、实现和测试了这个IPC问题的解决方案,它代表了Larry、Curly和Moe。使用信号量作为同步机制。“

我从给出的伪代码中输入了一个程序,但是我得到了错误:

代码语言:javascript
复制
project2part3.c:13:13: warning: initialization makes pointer from integer without a cast [-Wint-conversion] 
 #define MAX 5
             ^
project2part3.c:22:18: note: in expansion of macro 'MAX'
 sem_t unfilled = MAX;
                   ^
代码语言:javascript
复制
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>

#define MAX 5

void *larry();
void *moe();
void *curly();

pthread_mutex_t shovel = PTHREAD_MUTEX_INITIALIZER;
sem_t empty;
sem_t seeded;
sem_t unfilled;

int main(){
    pthread_t ltid;
    pthread_t mtid;
    pthread_t ctid;
    //initializing the semaphores
    sem_init(&empty, 0, 0);
    sem_init(&seeded, 0, 0);
    sem_init(&unfilled, 0, 0);

    pthread_create(&ltid, NULL, larry, NULL);  //create the larry thread
    pthread_create(&mtid, NULL, moe, NULL);  //create the moe thread
    pthread_create(&ctid, NULL, curly, NULL);  //create the curly thread

    pthread_join(ltid,NULL);
    pthread_join(mtid,NULL);
    pthread_join(ctid,NULL);
}

void *larry(){
    while(1){
        sem_wait(unfilled);
        sem_wait(shovel);
        //Dig the hole
        printf("Digging");
        sem_post(shovel);
        sem_post(empty);
    }
}

void *moe(){
    while(1){
        sem_wait(empty);
        //Seed the hole
        printf("Seeding");
        sem_post(seeded);
    }
}

void *curly(){
    while(1){
        sem_wait(seeded);
        sem_wait(shovel);
        //Fill the hole
        printf("Filling");
        sem_post(shovel);
        sem_post(unfilled);
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-04 15:05:24

代码语言:javascript
复制
sem_t shovel = 1; // Note: Is a lock in the updated question code
sem_t empty = 0;
sem_t seeded = 0;
sem_t unfilled = MAX;

这是而不是,您是如何初始化信号量的。它们是复杂的事物,而不仅仅是可以分配给它们的计数器。这就是为什么您使用的函数sem_init,但不正确。在你选择的推荐信中仔细阅读

IIRC sem_t是一个类似于

代码语言:javascript
复制
typedef struct whatever * sem_t;

因此,上面的每一行从一个整数初始化一个指针。

此外,您的函数应该返回声明返回的内容。对于用于线程的函数尤其如此:它们(需要)声明它们返回一个空指针,所以(如果您没有任何有意义的返回内容),只需使用

代码语言:javascript
复制
return NULL;

在这些东西的尽头。

此外:

代码语言:javascript
复制
pthread_create(&btid, NULL, larry, NULL);  //create the larry thread
pthread_create(&btid, NULL, moe, NULL);  //create the moe thread
pthread_create(&btid, NULL, curly, NULL);  //create the curly thread

您希望调用不同的thread_t,而不是全部调用相同的(btid)。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35799100

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档