c - 如何将 2 个进程“转换”为父子进程?
问题描述
所以我有这个很棒的代码,用于以前Ali Hasan Ahmed Khan的死锁的 C 示例。我只是在考虑将其转换为父子进程,因此以某种方式使 funcA 成为父进程,然后分叉 funcB。当我使用 fork 命令时,我在 main 中遇到了一个错误,说 funcB 不存在。这可以转换吗?完整的代码是:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/sem.h>
#define PERMS 0660
int semId;
int initSem(int semId, int semNum, int initValue) {
return semctl(semId, semNum, SETVAL, initValue);
}
// Try to take a resource, wait if not available
int P(int semId, int semNum) {
struct sembuf operationList[1];
operationList[0].sem_num = semNum;
operationList[0].sem_op = -1;
operationList[0].sem_flg = 0;
return semop(semId, operationList, 1);
}
// Release a resource
int V(int semId, int semNum) {
struct sembuf operationList[1];
operationList[0].sem_num = semNum;
operationList[0].sem_op = 1;
operationList[0].sem_flg = 0;
return semop(semId, operationList, 1);
}
void* funcA(void* nothing) {
printf("Thread A try to lock 0...\n");
P(semId, 0); // Take resource/semaphore 0 of semID
printf("Thread A locked 0.\n");
usleep(50*1000); // Wait 50 ms
printf("Thread A try to lock 1...\n");
P(semId, 1); // Take resource/semaphore 1 of semID
printf("Thread A locked 1.\n");
V(semId, 0); // Release resource/semaphore 0 of semID
V(semId, 1); // Release resource/semaphore 1 of semID
return NULL;
}
void* funcB(void* nothing) {
printf("Thread B try to lock 1...\n");
P(semId, 1);
printf("Thread B locked 1.\n");
usleep(5*1000);
printf("Thread B try to lock 0...\n");
P(semId, 0);
printf("Thread B locked 0.\n");
V(semId, 0);
V(semId, 1);
return NULL;
}
int main(int argc, char* argv[]) {
int i;
// ftok generates a key based on the program name and a char value
semId = semget(ftok(argv[0], 'A'), 2, IPC_CREAT | PERMS);
initSem(semId, 0, 1);
initSem(semId, 1, 1);
pthread_t thread[2];
pthread_create(&thread[0], NULL, funcA, NULL);
pthread_create(&thread[1], NULL, funcB, NULL);
for (i = 0 ; i < 2 ; i++) {
pthread_join(thread[i], NULL);
}
printf("This is not printed in case of deadlock\n");
semctl(semId, 0, IPC_RMID, 0);
semctl(semId, 1, IPC_RMID, 0);
return 0;
}
解决方案
推荐阅读
- python - 数据框列中的 Python 正则表达式
- python - TypeError: 'bool' 对象在使用 all() 时不可迭代
- sql - SQL 查询运行超过 CPU 使用限制
- python - How to create sprites around a location?
- ios - 多次调用 ViewDidLoad 将 SwiftUI 调用到情节提要?
- typescript - 如何在打字稿中获取范围数数组
- vim - 如何在vimscript中将搜索结果作为列表获取?
- python - 根据条件在 Jupyter Notebook 中显示 DataFrame
- c - MbedTLS 和 .NET BouncyCastle 与 Curve25519 的互操作性问题
- python - Django显示在不同字段中上传文件