代碼:
結構體RW_LOCK是實作讀/寫鎖,剩下的代碼是測驗資料
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
//pthread_rwlock_t
//pthread_mutex_t
//pthread_cond_t
class RW_LOCK{
public:
RW_LOCK(){
pthread_mutex_init(&mutex,NULL);
ref_t=0;
}
void writelock()
{
while (true)
{
pthread_mutex_lock(&mutex);
if(ref_t==0){
return ;
}
else{
pthread_mutex_unlock(&mutex);
}
}
}
void writeunlock()
{
pthread_mutex_unlock(&mutex);
}
void readlock()
{
pthread_mutex_lock(&mutex);
ref_t++;
pthread_mutex_unlock(&mutex);
}
void readunlock()
{
pthread_mutex_lock(&mutex);
ref_t--;
pthread_mutex_unlock(&mutex);
}
~RW_LOCK()
{
pthread_mutex_destroy(&mutex);
}
private:
pthread_mutex_t mutex;
int ref_t;
}rwmutex;
void* fill(void * nothing)
{
for(int i=1;i<=100;++i)
{
rwmutex.writelock();
printf("begin write.\n");
printf("end write.\n");
sleep(1);
rwmutex.writeunlock();
sleep(1);
}
return NULL;
}
void *know1(void *nothing)
{
for(int i=1;i<=100;++i)
{
rwmutex.readlock();
printf("begin read1.\n");
sleep(1);
printf("end read1.\n");
rwmutex.readunlock();
sleep(1);
}
return NULL;
}
void *know2(void *nothing)
{
for(int i=1;i<=100;++i)
{
rwmutex.readlock();
printf("begin read2.\n");
sleep(1);
printf("end read2.\n");
rwmutex.readunlock();
sleep(1);
}
return NULL;
}
int main()
{
pthread_t t1,t2,t3,t4;
pthread_create(&t1,NULL,fill,NULL);
pthread_create(&t2,NULL,know1,NULL);
pthread_create(&t3,NULL,know1,NULL);
pthread_create(&t4,NULL,know2,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_join(t3,NULL);
pthread_join(t4,NULL);
return 0;
}
經過測驗暫時沒有發現問題,但自己也不敢打保票呀
(萬一面試官問著了,自己寫了個錯的就尷尬了)
uj5u.com熱心網友回復:
代碼挺簡潔,邏輯上沒毛病,就是寫鎖成了自旋鎖了,相對比較耗資源。uj5u.com熱心網友回復:
如果能考慮寫的優先權可能更好uj5u.com熱心網友回復:
嗯嗯,我再想辦法改進一下。uj5u.com熱心網友回復:
面試官不問這個,面試官一般問屌得一比的問題,比如先來個熱身,什么是死鎖,什么情況下會死鎖?
然后,怎么檢測死鎖~~~~?
uj5u.com熱心網友回復:
哈哈哈,這東西口頭說一下還行,要是讓實作一個檢測死鎖的演算法那就GG了
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/95872.html
標籤:C++ 語言
上一篇:c++檔案自定義輸出范圍
