多进程之间的线程利用XSI IPC共享内存分配互斥量进行同步
··· #include <st … Read More
Socrates
···
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define handle_error_en(en, msg) \
do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
static pthread_mutex_t *mtx;
static void *original_owner_thread(void *ptr){
printf(“[original owner] Setting lock…\n”);
pthread_mutex_lock(mtx);
printf(“[original owner] Locked. Now exiting without unlocking.\n”);
pthread_exit(NULL);//加锁后退出不释放锁
}
int main(){
pid_t pid_robust;
int shmid;
//利用XSI IPC,分配互斥量的内存
shmid = shmget(IPC_PRIVATE,sizeof(pthread_mutex_t),IPC_CREAT|IPC_EXCL);
//获取内存区指针
mtx=shmat(shmid,0,0);
pid_robust = fork();
int proc_status;
int ret;
if(pid_robust <0 ){
printf(“[main process] fork error!\n”);
return -1;
}
if (pid_robust > 0){
pthread_t thr_p;
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr,PTHREAD_PROCESS_SHARED);
pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST);
pthread_mutex_init(mtx, &attr);
pthread_create(&thr_p, NULL, original_owner_thread, NULL);
}else if(0==pid_robust){
int err_code;
sleep(2);
printf(“[fork main thread] Attempting to lock the robust mutex.\n”);
err_code = pthread_mutex_lock(mtx);
if (err_code == EOWNERDEAD) {
printf(“[fork main thread] pthread_mutex_lock() returned EOWNERDEAD\n”);
printf(“[fork main thread] Now make the mutex consistent\n”);
err_code = pthread_mutex_consistent(mtx);//调用函数进行更换锁的属主,也就是锁从以前拥有者更换为当起线程
if (err_code != 0){
handle_error_en(err_code, “pthread_mutex_consistent”);
}
printf(“[fork main thread] Mutex is now consistent; unlocking\n”);
err_code = pthread_mutex_unlock(mtx);
if (err_code == 0 ){
printf(“[fork main thread] pthread_mutex_lock() unexpectedly succeeded\n”);
}else{
handle_error_en(err_code, “pthread_mutex_unlock”);
}
}else{
printf(“[fork main thread] lock success! %d\n”,err_code);
}
exit(0);
}
printf(“parent main thread waiting fork process \n”);
sleep(2);
if(waitpid(pid_robust,&proc_status,0) < 0){
printf(“[parent main thread] waiting for fork process error.\n”);
return 127;
}
if(WIFEXITED(proc_status)){
return 0;
}
return 127;
}
···
编译:
gcc -lpthread -o muti_proc_thread_lock muti_proc_thread_lock.c
结果:

参考:
相关文章
“放松与它在视觉中的作用”:这篇1977年完成的博士论文为现代人工智能研究的发展奠定了基础
当人们提到杰弗里·辛顿时,他们通常会想到反向传播算法、玻尔兹曼机、深度信念网络,以及那些彻底改变了人工智能发展的深度学习技术。 然而,很少有人会追溯到他科研生涯的起点。 1977年,在那篇著名的关于反向传播的论文发表之前的近十年时间里,辛顿在爱丁堡大学完成了他的博士论文,题为《松弛机制在视觉认知中的作用》。乍一看,这篇论文似乎只是探讨计算机视觉与松弛算法之间的关系。当我开始阅读它时,我也正是抱着这样的预期。 然而,在仔细研读之后,我意识到这篇论文涉及的远不止视觉算法。许多后来成为辛顿研究核心的理念,在当时就已经初具雏形。虽然当时的术语有所不同,数学表达也更为简单,神经网络也尚未成为他研究的重点
阅读全文
那些被隐藏起来的基础设施建设成本:为什么你的团队不应该再继续承担这些责任了
大多数工程团队最初并不是为了管理基础设施而开始工作的。他们通常是带着某个产品创意 … Read More
阅读全文