linux下为了多线程同步,通常用到锁的概念。posix下抽象了一个锁类型的结构:ptread_mutex_t。通过对该结构的操作,来判断资源是否可以访问。顾名思义,加锁(lock)后,别人就无法打开,只有当锁没有关闭(unlock)的时候才能访问资源。即对象互斥锁的概念,来保证共享数据操作的完整性。每个对象都对应于一个可称为" 互斥锁" 的标记,这个标记用来保证在任一时刻,只能有一个线程访问该对象。使用互斥锁(互斥)可以使线程按顺序执行。通常,互斥锁通过确保一次只有一个线程执行代码的临界段来同步多个线程。互斥锁还可以保护单线程代码。
互斥锁机制主要包括下面的基本函数:
互斥锁初始化:pthread_mutex_init();
互斥锁上锁:pthread_mutex_lock();
互斥锁判断上锁:pthread_mutex_trylock();
互斥锁解锁:pthread_mutex_unlock();
互斥锁销毁:pthread_mutex_destory();
下面我们写一个示例程序,该示例程序主要是模拟取款,同一时刻,只能有一个用户去取卡里的钱。
1 #include<stdio.h> 2 #include<pthread.h> 3 #include<stdlib.h> 4 #include<unistd.h> 5 6 pthread_mutex_t mutex; 7 int money = 10000; 8 9 void *pthread_zhangsan(void *arg) 10 { 11 int withdraw,balance,reality; 12 while (1) 13 { 14 if(pthread_mutex_lock(&mutex) == 0) 15 { 16 balance = money; 17 reality = 0; 18 printf("张三取款中---- "); 19 sleep(1); 20 printf("卡内余额:%d ",balance); 21 printf("请输入取款金额:"); 22 scanf("%d",&withdraw); 23 if(withdraw > balance) 24 { 25 printf("余额不足! "); 26 reality = 0; 27 } 28 else 29 { 30 balance = balance - withdraw; 31 money = balance; 32 reality = withdraw; 33 } 34 pthread_mutex_unlock(&mutex); 35 printf("张三要取%d,实际取了%d,卡内余额%d ",withdraw,reality,balance); 36 break; 37 } 38 else 39 { 40 printf("李四正在取钱 "); 41 sleep(1); 42 } 43 } 44 45 } 46 void *pthread_lisi(void *arg) 47 { 48 int withdraw,balance,reality; 49 while (1) 50 { 51 if(pthread_mutex_lock(&mutex) == 0) 52 { 53 balance = money; 54 reality = 0; 55 printf("李四取款中---- "); 56 sleep(1); 57 printf("卡内余额:%d ",balance); 58 printf("请输入取款金额:"); 59 scanf("%d",&withdraw); 60 if(withdraw > balance) 61 { 62 printf("余额不足! "); 63 reality = 0; 64 } 65 else 66 { 67 balance = balance - withdraw; 68 money = balance; 69 reality = withdraw; 70 } 71 pthread_mutex_unlock(&mutex); 72 printf("李四要取%d,实际取了%d,卡内余额%d ",withdraw,reality,balance); 73 break; 74 } 75 else 76 { 77 printf("张三正在取钱 "); 78 sleep(1); 79 } 80 } 81 } 82 int main(int argc, char const *argv[]) 83 { 84 pthread_t zhangsan,lisi; 85 pthread_mutex_init(&mutex,NULL); 86 if(pthread_create(&zhangsan,NULL,pthread_zhangsan,NULL) != 0) 87 { 88 perror("pthread_create"); 89 exit(1); 90 } 91 if(pthread_create(&lisi,NULL,pthread_lisi,NULL) != 0) 92 { 93 perror("pthread_create"); 94 exit(1); 95 } 96 pthread_join(zhangsan,NULL); 97 pthread_join(lisi,NULL); 98 pthread_mutex_destroy(&mutex); 99 return 0; 100 }
运行结果: