【发布时间】:2017-05-04 10:31:14
【问题描述】:
我有这段代码:
typedef struct
{
// ... other fields ...
pthread_mutex_t Lock;
} TShared;
const int NPROCESSES=32;
pid_t pidprocesses[128];
for (int i=0;i<NPROCESSES;i++)
{
pidprocesses[i]=fork();
if (!pidprocesses[i])
{
sleep(5); // wait the main process
int shmid = shmget(1616,sizeof(TShared),0666);
if (shmid<0)
{
printf("Error shmget!\n");
exit(0);
}
TShared *shm = (TShared *) shmat(shmid,NULL,0);
if (shm==-1)
{
printf("Error shmat!\n");
exit(0);
}
bool cond=true;
while(cond)
{
pthread_mutex_lock(&shm->Lock);
/* ... other code ... */
pthread_mutex_unlock(&shm->Lock);
}
exit(0);
}
}
// main process
int shmid = shmget(1616,sizeof(TShared),IPC_CREAT|0666);
if (shmid<0)
{
printf("Error shmget!\n");
exit(0);
}
TShared *shm = (TShared *) shmat(shmid,NULL,0);
if (shm==-1)
{
printf("Error shmat!\n");
exit(0);
}
pthread_mutex_init(&shm->Lock,NULL);
/* ... other code ... */
for (int i=0;i<NPROCESSES;i++) waitpid(pidprocesses[i],0,0);
这段代码创建了 32 个进程,然后使用共享内存和 pthread 互斥锁来同步它们,最后主进程等待子进程的终止。 这是使用 pthread 互斥锁的正确方法吗?
【问题讨论】:
标签: process pthreads mutex shared-memory