Fortran 信号量
谁能帮忙用 Fortran 写一个信号量函数?我有多个进程正在运行,我必须使用信号量来同步它们。对于 C++ 等可以找到这样的代码,但我找不到 fortran 的任何这样的代码。
如果我可以从 Fortran 代码调用 C/C++ 函数,那也足够了,因为 C++ 信号量函数已经存在。
PS:(附加说明)这是适用于 C++ 的代码。我有一些 Fortran 应用程序(作为标准基准测试的一部分),但没有信号量代码来同步它们。
int get_semaphore ()
{
int sem_id;
sem_id = semget(SEM_ID, 1, IPC_CREAT | 0666);
if (sem_id == -1) {
perror("get_semaphore: semget");
exit(1);
}
return sem_id;
}
int set_semaphore (int sem_id, int val)
{
return semctl(sem_id, 0, SETVAL, val);
}
void decrement_semaphore (int sem_id)
{
struct sembuf sem_op;
sem_op.sem_num = 0;
sem_op.sem_op = -1;
sem_op.sem_flg = 0;
semop(sem_id, &sem_op, 1);
}
void wait_semaphore (int sem_id)
{
struct sembuf sem_op;
sem_op.sem_num = 0;
sem_op.sem_op = 0;
sem_op.sem_flg = 0;
semop(sem_id, &sem_op, 1);
}
感谢您提前的帮助。
Can anyone help with writing a semaphore function in fortran? I have multiple processes running and I have to synchronize them using semaphore. Such a code could be found for C++ etc., but I could not find any such code for fortran.
If I could call C/C++ function from fortran code, that would also suffice, since C++ semaphore function is already there.
PS: (Additional Explanation) Here is the code which works for C++. I have some fortran applications (as part of standard benchmark) but no semaphore code to synchronize them.
int get_semaphore ()
{
int sem_id;
sem_id = semget(SEM_ID, 1, IPC_CREAT | 0666);
if (sem_id == -1) {
perror("get_semaphore: semget");
exit(1);
}
return sem_id;
}
int set_semaphore (int sem_id, int val)
{
return semctl(sem_id, 0, SETVAL, val);
}
void decrement_semaphore (int sem_id)
{
struct sembuf sem_op;
sem_op.sem_num = 0;
sem_op.sem_op = -1;
sem_op.sem_flg = 0;
semop(sem_id, &sem_op, 1);
}
void wait_semaphore (int sem_id)
{
struct sembuf sem_op;
sem_op.sem_num = 0;
sem_op.sem_op = 0;
sem_op.sem_flg = 0;
semop(sem_id, &sem_op, 1);
}
Thanks for the help in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
OpenMP 在术语“锁”下提供信号量。通常不会使用这些,因为 OpenMP 提供了更高级别的任务结构,但如果您想自己做,这可能是使用 Fortran 进行显式锁定/解锁的一种方法。
PS 如果您想通过调用已有的 C 代码来从 Fortran 中执行此操作,则可以使用 Fortran 2003 的 ISO C 绑定来完成。这里有很多关于其工作原理的问题/答案。我为您的 Fortran 程序起草了声明以匹配 C 例程。它们告诉 Fortran 编译器如何使用 C 编译器的调用约定来调用 C 例程。这些未经测试,可能需要调试:
OpenMP provides semaphores under the term "lock". Normally these aren't used since OpenMP provides higher level tasking constructs, but if you want to do it yourself, that could be a way to do explicit locking/unlocking with Fortran.
P.S. If you want to do it from Fortran by calling the C code that you already have, that could by done by using the ISO C Binding of Fortran 2003. There are many questions/answers here about how this works. I drafted declarations for your Fortran program to match the C routines. These tell the Fortran compiler how to call the C routines using the calling conventions of the C compiler. These are untested and may need debugging: