【发布时间】:2021-06-18 19:20:28
【问题描述】:
我想在 C 中实现 IPC:在某处放置一个屏障,以便不同的进程可以同时从该屏障开始运行。
我尝试了 pthread_barrier 和共享内存。进程 1 分配一块共享内存并在那里初始化一个 pthread_barrier 对象。然后,进程 2 将附加此共享内存并使用屏障。
我首先运行进程 1。但是,输出显示进程 2 执行正确(到达进程 1 已经在等待的屏障并继续前进),而进程 1 将永远挂起,似乎仍在等待。
这里是代码。
// process 1
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
/* initialize a shared variable in shared memory */
key_t shmkey = ftok("/dev/null", 5);
printf("shmkey for barrier = %d\n", shmkey);
int shmid = shmget(shmkey, sizeof(pthread_barrier_t), 0644 | IPC_CREAT);
if (shmid < 0)
{
perror("shmget\n");
exit(1);
}
pthread_barrier_t* pBarrier = (pthread_barrier_t*)shmat(shmid, NULL, 0); /* attach pBarrier to shared memory */
pthread_barrier_init(pBarrier, NULL, 2); /* barrier is initialized in shared memory, the number of waiting thread is 2 */
std::cout << "kernel 1 is ready" << std::endl;
pthread_barrier_wait(pBarrier);
std::cout << "kernel 1 i going" << std::endl;
return 0;
}
// process 2
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char** argv)
{
/* initialize a shared variable in shared memory */
key_t shmkey = ftok("/dev/null", 5);
printf("shmkey for barrier = %d\n", shmkey);
int shmid = shmget(shmkey, sizeof(pthread_barrier_t), 0644 | IPC_CREAT);
if (shmid < 0)
{
perror("shmget\n");
exit(1);
}
pthread_barrier_t* pBarrier = (pthread_barrier_t*)shmat(shmid, NULL, 0); /* attach pBarrier to shared memory */
std::cout << "kernel 2 will sleep for 5 secondes" << std::endl;
sleep(5);
std::cout << "kernel 2 is ready" << std::endl;
pthread_barrier_wait(pBarrier);
std::cout << "kernel 2 is going" << std::endl;
/* Clean the shared memory */
// sleep(3);
// shmdt(pBarrier);
// shmctl(shmid, IPC_RMID, NULL);
return 0;
}
[output][1]
[1]: https://i.stack.imgur.com/dEx91.png
【问题讨论】:
标签: c pthreads ipc shared-memory