问题陈述:
“拉里、莫伊和卷毛正在播种。拉里挖洞,然后在每个洞里放一粒种子。卷曲然后填满这个洞。有几个同步限制:
设计、实现和测试了这个IPC问题的解决方案,它代表了Larry、Curly和Moe。使用信号量作为同步机制。“
我从给出的伪代码中输入了一个程序,但是我得到了错误:
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;
^#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(<id, 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);
}
}发布于 2016-03-04 15:05:24
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是一个类似于
typedef struct whatever * sem_t;因此,上面的每一行从一个整数初始化一个指针。
此外,您的函数应该返回声明返回的内容。对于用于线程的函数尤其如此:它们(需要)声明它们返回一个空指针,所以(如果您没有任何有意义的返回内容),只需使用
return NULL;在这些东西的尽头。
此外:
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)。
https://stackoverflow.com/questions/35799100
复制相似问题