互斥锁,读写锁

网友投稿 558 2022-10-21

互斥锁,读写锁

互斥锁,读写锁

一、互斥量(互斥锁)

将输出作为共享资源,加锁,进行父线程输出大写HELLO WORLD,子线程输出小写hello world,利用随机数,使得睡眠时间,模拟线程占用cpu时间,

调用pthread_mutex_init初始化的互斥锁,在释放内存前需要调用pthread_mutex_destroy

#include#include#include#include#includepthread_mutex_t mutex; //锁的定义void *tfn(void *arg){ srand(time(NULL)); while(1){ pthread_mutex_lock(&mutex); printf("hello"); sleep(rand() % 3); /*模拟长时间操作共享资源,导致cpu易主,产生与时间>有关的错误*/ printf("world\n"); pthread_mutex_unlock(&mutex); sleep(rand() % 3); } return NULL;}int main(void){ pthread_t tid; srand(time(NULL)); pthread_mutex_init(&mutex,NULL); //mutex == 1 pthread_create(&tid,NULL,tfn,NULL); while(1){ pthread_mutex_lock(&mutex); printf("HELLO"); sleep(rand()%3); printf("WORLD\n"); pthread_mutex_unlock(&mutex); //将 unlock 挪至第二个 sleep 后,发现交替现象很难出现。//线程在操作完共享资源后本应该立即解锁,但修改后,线程抱着锁睡眠。睡醒解锁后又立即加锁,这将导致其他线程很难抢到锁 sleep(rand() % 3); } pthread_mutex_destroy(&mutex);}

二、读写锁,同时多个进程多共享数据进行读写操作,,读共享,写独占,读写并行阻塞是,写的优先级高

#include #include#includeint counter; //全局资源pthread_rwlock_t rwlock;void *th_write(void *arg) //写线程{ int t; int i = (int)arg; while(1){ t = counter; usleep(1000); pthread_rwlock_wrlock(&rwlock); printf("========write %d: %lu: counter=%d ++counter=%d\n",i,pthread_self(),t,++counter); pthread_rwlock_unlock(&rwlock); usleep(5000); } return NULL;}void *th_read(void *arg){ int i = (int)arg; while(1){ pthread_rwlock_rdlock(&rwlock); printf("---------read %d: %lu: %d\n",i,pthread_self(),counter); pthread_rwlock_unlock(&rwlock); usleep(900); } return NULL;}int main(void){ int i; pthread_t tid[8]; pthread_rwlock_init(&rwlock,NULL); for(i = 0; i < 3; i++) pthread_create(&tid[i],NULL,th_write,(void *)i); for(i = 0; i < 5; i++) pthread_create(&tid[i+3],NULL,th_read,(void *)i); //三个写线程,5个读线程 for(i = 0; i < 8; i++) pthread_join(tid[i],NULL); pthread_rwlock_destroy(&rwlock); //释放读写锁 return 0;}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:一个PHP序列化程序,可生成PHP代码以获得最佳性能
下一篇:MLton 是整个程序的优化编译器的标准ML编程语言
相关文章

 发表评论

暂时没有评论,来抢沙发吧~