【发布时间】:2021-09-25 03:26:17
【问题描述】:
我有两个 C 文件:a.c (master) 和 b.c (follower)。
我想使用信号量在 master 和 follower 之间创建同步。
根据我了解到的情况,我需要一个全局 POSIX 信号量才能完成这项工作。
如何仅使用 a.c (master) 中的信号量在 b.c (follower) 文件中实现这一点?
为a.c 文件(主)实现的信号量:
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
sem_t x,y;
pthread_t tid;
pthread_t writerthreads[100],readerthreads[100];
int readercount = 0, writercount = 0;
void* reader(void* param)
{
if (writercount > 0) {
sem_wait(&x);
readercount++;
if (readercount == 1) {
sem_wait(&y);
}
sem_post(&x);
printf("%d reader is inside\n",readercount);
//read all the files in the directory
sleep(3);
sem_wait(&x);
readercount--;
if (readercount == 0) {
sem_post(&y);
}
sem_post(&x);
printf("%d Reader is leaving\n",readercount+1);
} else {
printf("Nothing to view\n");
}
return NULL;
}
void* writer(void* param)
{
printf("Master is trying to upload\n");
sem_wait(&y);
printf("Master is uploading\n");
//create file in a directory
sem_post(&y);
writercount++;
printf("Master is leaving\n");
return NULL;
}
int main()
{
int a,i = 0,b;
sem_init(&x,0,1);
sem_init(&y,0,1);
while (1) {
printf("Enter 1 to View / 2 to Upload / 3 to Exit:");
scanf("%d",&b);
if (b == 1) {
pthread_create(&readerthreads[i],NULL,reader,NULL);
} else if (b == 2) {
pthread_create(&writerthreads[i],NULL,writer,NULL);
} else {
exit(0);
}
pthread_join(writerthreads[i],NULL);
pthread_join(readerthreads[i],NULL);
i++;
}
return 0;
}
b.c 文件中的信号量(关注者):
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
sem_t x,y;
pthread_t tid;
pthread_t readerthreads[100];
int readercount = 0, writercount = 0;
void* reader(void* param)
{
if (writercount > 0) {
sem_wait(&x);
readercount++;
if (readercount == 1) {
sem_wait(&y);
}
sem_post(&x);
printf("%d Follower is inside\n",readercount);
//read all the files in the directory
sleep(3);
sem_wait(&x);
readercount--;
if (readercount == 0) {
sem_post(&y);
}
sem_post(&x);
printf("%d Follower is leaving\n",readercount+1);
} else {
printf("Nothing to view\n");
}
return NULL;
}
int main()
{
int a,i = 0,b;
sem_init(&x,0,1);
sem_init(&y,0,1);
while (1) {
printf("Enter 1 to View / 3 to Exit:");
scanf("%d",&b);
if (b == 1) {
pthread_create(&readerthreads[i],NULL,reader,NULL);
} else {
exit(0);
}
pthread_join(readerthreads[i],NULL);
i++;
}
}
【问题讨论】:
-
具体而言,请参阅 man7.org/linux/man-pages/man3/sem_open.3.html,其中提到您必须使用
sem_open()来创建或打开命名信号量,并且您为信号量提供的名称必须以/。还要确保名称是唯一的,因为系统上的其他进程也使用全局信号量,并且您不希望您的名称与其他进程发生冲突。 -
@NikosC.,是的,它很有用,但我可以看到它的示例实现吗?