rwlock3.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include <pthread.h>
  2. #include <unistd.h>
  3. #include <iostream>
  4. int resourceID = 0;
  5. pthread_rwlock_t myrwlock;
  6. void* read_thread(void* param)
  7. {
  8. while (true)
  9. {
  10. //请求读锁
  11. pthread_rwlock_rdlock(&myrwlock);
  12. std::cout << "read thread ID: " << pthread_self() << ", resourceID: " << resourceID << std::endl;
  13. //使用睡眠模拟读线程读的过程消耗了很久的时间
  14. sleep(1);
  15. pthread_rwlock_unlock(&myrwlock);
  16. }
  17. return NULL;
  18. }
  19. void* write_thread(void* param)
  20. {
  21. while (true)
  22. {
  23. //请求写锁
  24. pthread_rwlock_wrlock(&myrwlock);
  25. ++resourceID;
  26. std::cout << "write thread ID: " << pthread_self() << ", resourceID: " << resourceID << std::endl;
  27. pthread_rwlock_unlock(&myrwlock);
  28. //放在这里增加请求读锁线程获得锁的几率
  29. sleep(1);
  30. }
  31. return NULL;
  32. }
  33. int main()
  34. {
  35. pthread_rwlockattr_t attr;
  36. pthread_rwlockattr_init(&attr);
  37. //设置成请求写锁优先
  38. pthread_rwlockattr_setkind_np(&attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
  39. pthread_rwlock_init(&myrwlock, &attr);
  40. //创建5个请求读锁线程
  41. pthread_t readThreadID[5];
  42. for (int i = 0; i < 5; ++i)
  43. {
  44. pthread_create(&readThreadID[i], NULL, read_thread, NULL);
  45. }
  46. //创建一个请求写锁线程
  47. pthread_t writeThreadID;
  48. pthread_create(&writeThreadID, NULL, write_thread, NULL);
  49. pthread_join(writeThreadID, NULL);
  50. for (int i = 0; i < 5; ++i)
  51. {
  52. pthread_join(readThreadID[i], NULL);
  53. }
  54. pthread_rwlock_destroy(&myrwlock);
  55. return 0;
  56. }