生活随笔
收集整理的這篇文章主要介紹了
linux知识(二)互斥量、信号量和生产者消费者模型
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
linux知識(二)互斥量、信號量和生產者消費者模型
一、互斥量
產生原因
使用多線程常常會碰到數據混亂的問題,那么使用互斥量,相當于“加鎖”的操作,將有助于解決數據混亂的問題
每個線程在對資源操作前都嘗試先加鎖,成功加鎖才能操作,操作結束解鎖
資源還是共享的,線程間也還是競爭的,
但通過“鎖”就將資源的訪問變成互斥操作,而后與時間有關的錯誤也不會再產生了。
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>pthread_mutex_t mutex
;
void* tfn(void* arg
)
{srand(time(NULL));while (1) {pthread_mutex_lock(&mutex
);printf("hello ");sleep(rand() % 3); printf("world\n");pthread_mutex_lock(&mutex
);pthread_mutex_unlock(&mutex
);sleep(rand() % 3);}return NULL;
}int main(void)
{int flg
= 5;pthread_t tid
;srand(time(NULL));pthread_mutex_init(&mutex
,NULL); pthread_create(&tid
,NULL,tfn
,NULL);while (1) {pthread_mutex_lock(&mutex
);printf("HELLO ");sleep(rand() % 3);printf("WORLD\n");pthread_mutex_unlock(&mutex
);sleep(rand() % 3);}pthread_cancel(tid
);pthread_join(tid
, NULL);pthread_mutex_destroy(&mutex
);return 0;
}
二、信號量
互斥量的操作是1對1的,一個線程加鎖與解鎖完成后,下一個線程通過競爭在拿到鎖進行操作,對于多線程并發來說,無形間效率就變低了。多個線程間對某一對象的部分數據進行共享,使用互斥鎖是沒有辦法實現的,只能將整個數據對象鎖住。線程從并行執行,變成了串行執行。與直接使用單進程無異。信號量能有效的解決這一問題。
生產者消費者模型
說到信號量,就必須提到生產者消費者模型
我們來假設一下這樣一個情景,圖中有生產者,消費者以及有5個盤子。生產者只有生產了,消費者才能拿到東西。我們定義5個線程來當作生產者持續生產,它們需要拿到盤子來生產,它們不在像用拿“鎖”的方式一個一個來生產,這樣無形之中就提高了效率,提高了并發型。消費等生產者生產完,通過競爭來搶這些消費品。
#include <cstdio>
#include <pthread.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <string.h>using namespace std
;
int g_count
=0;
pthread_mutex_t prod_mutex
;
pthread_mutex_t cur_mutex
;
sem_t g_sem_prod
;
sem_t g_sem_cur
; void * add(void *arg
)
{cout
<< " thread .. wait .. id = " << pthread_self() << endl
;sem_wait(&g_sem_prod
);pthread_mutex_lock(&prod_mutex
);g_count
++;printf("make cake ... g_count = %d\n",g_count
);pthread_mutex_unlock(&prod_mutex
);sem_post(&g_sem_cur
);sleep(rand() % 3);}void* sub(void* arg
)
{cout
<< "wait cake thread .. wait .. id = " << pthread_self() << endl
;sem_wait(&g_sem_cur
);pthread_mutex_lock(&cur_mutex
);g_count
--;printf("eat.......g_count = %d\n", g_count
);pthread_mutex_unlock(&cur_mutex
);sem_post(&g_sem_prod
);sleep(rand() % 3);}int main()
{int i
= 0;pthread_t tid
;int ret
;pthread_mutex_init(&prod_mutex
,NULL);pthread_mutex_init(&cur_mutex
, NULL);sem_init(&g_sem_prod
,0,5);sem_init(&g_sem_cur
,0, 0);for (i
= 0; i
< 5; i
++){ret
= pthread_create(&tid
, NULL, add
, NULL);if (ret
!= 0){cout
<< strerror(ret
) << endl
;return 0;}}for (i
= 0; i
< 5; i
++){ret
=pthread_create(&tid
, NULL, sub
, NULL);if (ret
!= 0){cout
<< strerror(ret
) << endl
;return 0;}}while (1){}return 0;
}
總結
以上是生活随笔為你收集整理的linux知识(二)互斥量、信号量和生产者消费者模型的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。