1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| #include "init.h" #define PERR(msg) \ do { perror(msg); exit(-1); } while(0) #define PPERR(err,msg) \ do { err=errno; perror(msg); exit(-1); } while(0)
struct ticket { int remain; pthread_mutex_t lock; };
void printshared(pthread_mutexattr_t *attr) { int err,shared; err = pthread_mutexattr_getpshared(attr,&shared); if (err != 0) PPERR(err,"pthread_mutexattr_getshared"); if (shared == PTHREAD_PROCESS_PRIVATE) puts("shared = PTHREAD_PROCESS_PRIVATE"); else if (shared == PTHREAD_PROCESS_SHARED) puts("shared = PTHREAD_PROCESS_SHARED"); else puts("shared = ???"); }
void printrobust(pthread_mutexattr_t *attr) { int err,robust; err = pthread_mutexattr_getrobust(attr,&robust); if (err != 0) PPERR(err,"pthread_mutexattr_getrobust"); if (robust == PTHREAD_MUTEX_STALLED) puts("robust = PTHREAD_MUTEX_STALLED"); else if (robust == PTHREAD_MUTEX_ROBUST) puts("robust = PTHREAD_MUTEX_ROBUST"); else puts("robust = ???"); }
int main(int argc,char *argv[]) { int err,shared,robust = 0,flag = 1; robust = 1; key_t key = 0x8888;
int id = shmget(key,getpagesize(),IPC_CREAT | IPC_EXCL | 0666); if (id < 0) PERR("shmget");
struct ticket *t = (struct ticket *)shmat(id,NULL,0);
if (t == (void *)-1) PERR("shmat");
t->remain = 10;
pthread_mutexattr_t mutexattr; err = pthread_mutexattr_init(&mutexattr); if (err != 0) PPERR(err,"pthread_mutexattr_init");
printshared(&mutexattr); printrobust(&mutexattr);
shared = PTHREAD_PROCESS_SHARED; err = pthread_mutexattr_setpshared(&mutexattr,shared); if (err != 0) PPERR(err,"pthread_mutexattr_setpshared"); if (robust) { err = pthread_mutexattr_setrobust(&mutexattr,PTHREAD_MUTEX_ROBUST); if (err != 0) PPERR(err,"pthread_mutexattr_setrobust"); }
puts("modify attribute ----------------------"); printshared(&mutexattr); printrobust(&mutexattr);
pthread_mutex_init(&t->lock,&mutexattr); err = pthread_mutexattr_destroy(&mutexattr); if (err != 0) PPERR(err,"pthread_mutexattr_destroy"); err = shmdt((void *)t); if (err != 0) PERR("shmdt"); return 0; }
|