執行緒安全
概念:多個執行緒對臨界資源的訪問是安全的;
實作:同步與互斥
-
互斥:通過同一時間對臨界資源的唯一訪問保證訪問操作的安全;
-
同步:通過條件判斷使對臨界資源的訪問更加合理;
互斥的實作:
互斥鎖:本質是一個個0/1技術器,用于標記對臨界資源的訪問;
0——不可訪問,1——可訪問;
互斥鎖自身操作是一個原子操作(直接用0與臨界資源進行交換,然后判斷臨界資源可否訪問):
//linux,列印會出錯
//多執行緒列印,判斷不及時,多執行緒進入導致--過多,列印錯誤
#include<stdio.h>
2 #include<pthread.h>
3
4 int tickets=100;
5 void *scalpers(void *arg){
6 while(1){
7 if(tickets>0){
8 usleep(1);
9 printf("i get a ticket:%d\n",tickets);
10 tickets--;
11 }
12 else{
13 pthread_exit(NULL);
14 }
15 }
16 return NULL;
17 }
18 int main(int argc,int *argv[])
19 {
20 pthread_t tid[4];
21 int ret;
22 int i=0;
23 for(i=0;i<4;++i){
24 ret=pthread_create(&tid[i],NULL,scalpers,NULL);
25 if(ret!=0){
26 printf("create error\n");
27 return -1;
28 }
29 }
30 int j=0;
31 for(j=0;j<4;++j){
32 pthread_join(tid[j],NULL);
33
34 }
35 return 0;
36 }
介面介紹
1.定義互斥鎖變數:
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
2. 初始化互斥鎖(執行緒創建之前):
int pthread_mutex_init(pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr);
//mutex:要初始化的互斥量;
// attr:NULL
3.在臨界資源訪問之前加鎖:
int pthread_mutex_lock(pthread_mutex_t *mutex);
//——阻塞介面
int pthread_mutex_trylock(pthread_mutex_t *mutex);
//——非阻塞介面
4.在臨界資源訪問完畢后解鎖:
int pthread_mutex_unlock(pthread_mutex_t *mutex);
5.銷毀互斥鎖:
int pthread_mutex_destroy(pthread_mutex_t *mutex);
代碼如下
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <stdlib.h>
4 #include <pthread.h>
5
6 int tickets = 100;
7
8 void *scalpers(void *arg)
9 {
10 pthread_mutex_t *mutex = (pthread_mutex_t*)arg;
11 while(1) {
12 pthread_mutex_lock(mutex);//3.加鎖
13 if (tickets > 0) {
14 usleep(1);
15 printf("I got a ticket:%d\n", tickets);
16 tickets--;
17 }else {
18 pthread_mutex_unlock(mutex);//4.解鎖
19 pthread_exit(NULL);
20 }
21 pthread_mutex_unlock(mutex);//4.解鎖
22 }
23 return NULL;
24 }
25 int main (int argc, char *argv[])
26 {
27 pthread_mutex_t mutex;//1.定義互斥鎖變數
28 pthread_t tid[4];
29 int ret;
30 pthread_mutex_init(&mutex, NULL);//2.初始化互斥鎖
31 int i=0;
32 for(i = 0; i < 4; i++) {
33 ret = pthread_create(&tid[i], NULL, scalpers, &mutex);
34 if (ret != 0) {
35 printf("thread create error\n");
36 return -1;
37 }
38 }
39 int j=0;
40 for (j = 0; j < 4; j++) {
41 pthread_join(tid[j], NULL);
42 }
43 pthread_mutex_destroy(&mutex);//5.銷毀互斥鎖
44 return 0;
45 }
執行緒的知識點:
https://blog.csdn.net/weixin_52270223/article/details/115820547
下個一博客介紹死鎖的知識點;
如有錯誤或者補充,評論下;互相學習,互關一波,抱拳了
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/278022.html
標籤:其他
上一篇:Vue(基于 Visual Studio Code 編輯器)
下一篇:【最全干貨】SQL注入大合集

