prg8_5.c
来自「配套光盘网络编程进程间的通信,网络编程进程间的通信是一本很经典的好书」· C语言 代码 · 共 51 行
C
51 行
#include <stdlib.h>
#include <semaphore.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/stat.h>
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
pthread_t tid1,tid2;
void *thread1(void*),*thread2(void*);
int main(int argc,char **argv)
{
void *status;
pthread_setconcurrency(2);
pthread_create(&tid1,NULL,thread1,NULL);
sleep(1);
pthread_create(&tid2,NULL,thread2,NULL);
pthread_join(tid2,&status);
if (status != PTHREAD_CANCELED)
printf("thread2 status= %p\n",status);
pthread_join(tid1,&status);
if (status != NULL)
printf("thread1 status = %p\n",status);
pthread_rwlock_destroy(&rwlock);
exit(0);
}
void *thread1(void *arg)
{
pthread_rwlock_rdlock(&rwlock);
printf("thread1() got a read lock\n");
sleep(3);
pthread_cancel(tid2);
sleep(3);
pthread_rwlock_unlock(&rwlock);
return (NULL);
}
void *thread2(void *arg)
{
printf("thread2() trying to obtain a write lock\n");
pthread_rwlock_wrlock(&rwlock);
printf("thread2() got a write lock\n");
sleep(1);
pthread_rwlock_unlock(&rwlock);
return (NULL);
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?