Structure RW_LOCK is to realize the read/write lock, and the rest of the code is test data
# include & lt; Pthread. H>
# include & lt; stdio.h>
# include & lt; Unistd. H>
//pthread_rwlock_t
//pthread_mutex_t
//pthread_cond_t
The class RW_LOCK {
Public:
RW_LOCK () {
Pthread_mutex_init (& amp; Mutex, NULL);
Ref_t=0;
}
Void writelock ()
{
While (true)
{
Pthread_mutex_lock (& amp; Mutex);
If (ref_t==0) {
return ;
}
The else {
Pthread_mutex_unlock (& amp; Mutex);
}
}
}
Void writeunlock ()
{
Pthread_mutex_unlock (& amp; Mutex);
}
Void readlock ()
{
Pthread_mutex_lock (& amp; Mutex);
Ref_t + +;
Pthread_mutex_unlock (& amp; Mutex);
}
Void readunlock ()
{
Pthread_mutex_lock (& amp; Mutex);
Ref_t -;
Pthread_mutex_unlock (& amp; Mutex);
}
~ RW_LOCK ()
{
Pthread_mutex_destroy (& amp; Mutex);
}
Private:
pthread_mutex_t mutex;
Int ref_t;
} rwmutex;
Void * the fill nothing (void *)
{
for(int i=1; i<=100; + + I)
{
Rwmutex. Writelock ();
Printf (" the begin write. \ n ");
Printf (" end write. \ n ");
Sleep (1);
Rwmutex. Writeunlock ();
Sleep (1);
}
Return NULL;
}
Void * know1 nothing (void *)
{
for(int i=1; i<=100; + + I)
{
Rwmutex. Readlock ();
Printf (" the begin read1. \ n ");
Sleep (1);
Printf (" end read1. \ n ");
Rwmutex. Readunlock ();
Sleep (1);
}
Return NULL;
}
Void * know2 nothing (void *)
{
for(int i=1; i<=100; + + I)
{
Rwmutex. Readlock ();
Printf (" the 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 (& amp; T1, NULL, the fill, NULL);
Pthread_create (& amp; T2, NULL, know1, NULL);
Pthread_create (& amp; T3, NULL, know1, NULL);
Pthread_create (& amp; T4, NULL, know2, NULL);
Pthread_join (t1, NULL);
Pthread_join (t2, NULL);
Pthread_join (t3, NULL);
Pthread_join (t4, NULL);
return 0;
}
Tested had not found the problem, but also ah please (one thousand the interviewer asked him, he wrote a wrong just embarrassing)
CodePudding user response:
There is nothing wrong with code is pretty simple, logical, is writing a spin lock, lock is relatively expensive,CodePudding user response:
Priority would be better if you can considerCodePudding user response: