【发布时间】:2013-10-10 22:32:47
【问题描述】:
我想创建 n 个并行运行的进程并让它们锁定一个互斥体,增加一个计数器,然后解锁并退出。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <unistd.h>
#include <pthread.h>
pthread_mutex_t mutex;
int main(int argc, char **argv) {
if (argc != 2)
return 0;
int n = atoi(argv[1]);
int i = 0;
int status = 0;
pthread_mutex_init(&mutex, NULL);
pid_t pid = 1;
static int *x;
x = mmap(NULL, sizeof *x, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
*x = 0;
printf("Creating %d children\n", n);
for(i = 0; i < n; i++) {
if (pid != 0)
pid = fork();
}
if (pid == 0) {
pthread_mutex_lock(&mutex);
*x = *x + 1;
printf("[CHLD] PID: %d PPID: %d X: %d\n", getpid(), getppid(), *x);
pthread_mutex_unlock(&mutex);
exit(0);
}
wait(&status);
printf("[PRNT] PID: %d X: %d\n", getpid(), *x);
munmap(x, sizeof *x);
return 0;
}
./procs 10000 但是不会返回 x=10000 我认为这是因为互斥锁没有在进程之间共享,但是共享互斥锁的正确方法是什么?
【问题讨论】:
-
我认为在与
fork()进行交互时,您会发现使用信号量更容易。见man7.org/linux/man-pages/man7/sem_overview.7.html 和见stackoverflow.com/questions/6477525/… -
我有点想使用互斥锁,因为我想实现一个使用相同互斥锁的线程版本
-
也可以在线程中使用信号量,但当然互斥体更适合。如果你有兴趣,我做了一个使用信号量的例子。在这里查看:codepad.org/m1I9753u 与 -pthread 的链接
标签: c process parallel-processing fork mutex