您好,登錄后才能下訂單哦!
這篇文章主要介紹了C/C++中多進(jìn)程之間的線程如何利用XSI IPC共享內(nèi)存分配互斥量進(jìn)行同步,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
#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,分配互斥量的內(nèi)存
shmid = shmget(IPC_PRIVATE,sizeof(pthread_mutex_t),IPC_CREAT|IPC_EXCL);
//獲取內(nèi)存區(qū)指針
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);//調(diào)用函數(shù)進(jìn)行更換鎖的屬主,也就是鎖從以前擁有者更換為當(dāng)起線程
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
結(jié)果:
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“C/C++中多進(jìn)程之間的線程如何利用XSI IPC共享內(nèi)存分配互斥量進(jìn)行同步”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。