互斥锁
互斥锁-多线程
1 #include <stdio.h> 2 #include <unistd.h> 3 #include<signal.h> 4 #include <stdlib.h> 5 #include <pthread.h> 6 #include "../headx.h" 7 8 9 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 静态的初始化锁 10 11 void test_xxx(void) 12 { 13 int num = 0; 14 do { 15 pthread_mutex_lock(&mutex); 16 dbg("线程 %d", num++); 17 pthread_mutex_unlock(&mutex); 18 usleep(1); 19 } while(1); 20 } 21 22 int main(void) 23 { 24 dbg("互斥锁-线程"); 25 26 pthread_t thread; 27 if(pthread_create(&thread, NULL, V(test_xxx), NULL)) dbge(); 28 do { 29 pthread_mutex_lock(&mutex); 30 sleep(2); 31 pthread_mutex_unlock(&mutex); 32 33 /* 34 * 必须加一个延时 35 * 因为刚释放,刚好CPU时间还没用完, 36 * 又立马加锁了,导致资源一直被当前进程占用 37 */ 38 usleep(1); 39 } while(1); 40 } 41 42 // gcc 2.互斥锁.c -pthread
互斥锁-多进程
1 #include <stdio.h> 2 #include <unistd.h> 3 #include<signal.h> 4 #include <stdlib.h> 5 #include <pthread.h> 6 #include "../headx.h" 7 8 9 static void inline *anonymous_mmap_init(void) 10 { 11 void *addr = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0); 12 if(V(-1) == addr) dbge(); 13 return addr; 14 } 15 16 static void inline *process_mutex_init(void) 17 { 18 pthread_mutexattr_t mutex_attr; // 互斥锁属性 19 pthread_mutexattr_init(&mutex_attr); // 初始化互斥锁属性 20 21 // 设置互斥对象为PTHREAD_PROCESS_SHARED共享,即可以在多个进程的线程访问,PTHREAD_PROCESS_PRIVATE为同一进程的线程共享 22 pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED); 23 24 // 设置同步健壮属性 (https://blog.csdn.net/qq_31442743/article/details/105025450) 25 pthread_mutexattr_setrobust(&mutex_attr, PTHREAD_MUTEX_ROBUST); 26 27 pthread_mutex_t* shm_mutex = anonymous_mmap_init(); 28 pthread_mutex_init(shm_mutex, &mutex_attr); // 动态的初始化锁 29 30 return shm_mutex; 31 } 32 33 int main(void) 34 { 35 dbg("互斥锁-进程"); 36 pthread_mutex_t* shm_mutex = process_mutex_init(); 37 38 int pid; 39 if(-1 == (pid = fork())) dbge(); 40 if(!pid) { 41 uint num = 0; 42 do { 43 pthread_mutex_lock(shm_mutex); 44 dbg("子进程 %d", num++); 45 pthread_mutex_unlock(shm_mutex); 46 usleep(1); 47 } while(1); 48 } 49 do { 50 pthread_mutex_lock(shm_mutex); 51 sleep(2); 52 pthread_mutex_unlock(shm_mutex); 53 usleep(1); 54 } while(1); 55 } 56 57 58 // gcc 2.互斥锁.c -pthread 59 60 // https://blog.csdn.net/quantum7/article/details/85049258