线程同步2

时间锁

1
2
3
#include <pthread.h>
#include <time.h>
int pthread_mutex_timedlock(pthread_mutex_t * restrict mutex, const struct timespec *restrict tsptr);

愿意等待timespec描述的时间,达到时间返回错误码ETIMEOUT
一个例子

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// APUE example11-13                                       
// pthread_mutex_timedlock                                 
// lcl 20190325                                            
//                                                         
#include "../myapue.h"                                     
#include <pthread.h>                                       
#include <time.h>                                          

int main (void)                                            
{                                                          
    int err;                                               
    struct timespec tout;                                  
    struct tm *tmp;                                        
    char buf[64];                                          
    pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;      

    pthread_mutex_lock(&lock);                             
    printf("the mutex now is locked\n");                   
    clock_gettime(CLOCK_REALTIME, &tout);                  
    tmp = localtime(&tout.tv_sec);                         
    strftime(buf, sizeof(buf), "%r", tmp);                 
    printf("current time is %s\n",buf);                    

    tout.tv_sec += 10;                                     
    err = pthread_mutex_timedlock(&lock,&tout);            

    clock_gettime(CLOCK_REALTIME, &tout);                  
    tmp = localtime(&tout.tv_sec);                         
    strftime(buf,sizeof(buf), "%r", tmp);                  
    printf("the time is now %s\n",buf);                    

    if(err == 0)                                           
      printf("mutex locked again!\n");                     
    else                                                   
      printf("can't lock mutex again:%s\n",strerror(err));
    exit(0);                                               
}                                                          


运行结果:

1
2
3
4
the mutex now is locked
current time is 01:08:51 PM
the time is now 01:09:01 PM
can't lock mutex again:Connection timed out

读写锁,三种状态读加锁、写加锁和不加锁

1
2
3
4
5
6
7
8
#include <pthread.h>
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,
                                      const pthread_rwlockattr_t *restrict attr);
int pthread_rwlock_destory(pthread_rwlock_t *rwlock);

int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock)
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock)
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock)

如上,函数名可以很好的反映函数的功能。

  • 写锁阻塞其他加锁
  • 读锁阻塞写锁但不阻塞读锁
  • 写锁在阻塞时,不再响应其他读锁请求。