example_tc_file_lock.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. * Tencent is pleased to support the open source community by making Tars available.
  3. *
  4. * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
  5. *
  6. * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  7. * in compliance with the License. You may obtain a copy of the License at
  8. *
  9. * https://opensource.org/licenses/BSD-3-Clause
  10. *
  11. * Unless required by applicable law or agreed to in writing, software distributed
  12. * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  13. * CONDITIONS OF ANY KIND, either express or implied. See the License for the
  14. * specific language governing permissions and limitations under the License.
  15. */
  16. #include "util/tc_file_mutex.h"
  17. #include <unistd.h>
  18. #include <iostream>
  19. using namespace tars;
  20. void ThreadEntry1(TC_FileMutex *fl)
  21. {
  22. int i = 1;
  23. while(i == 0)
  24. {
  25. fl->rlock();
  26. cout << i << ":" << std::this_thread::get_id() << " : 1234567890abcdefghijklmnopqrstuvwxyz" << endl;
  27. sleep(1);
  28. cout << i << ":" << std::this_thread::get_id() << " : 1234567890abcdefghijklmnopqrstuvwxyz" << endl;
  29. // fl->unlock();
  30. sleep(1);
  31. i++;
  32. }
  33. }
  34. void ThreadEntry2(TC_FileMutex *fl)
  35. {
  36. int i = 1;
  37. while(i == 0)
  38. {
  39. fl->wlock();
  40. cout << i << ":" << std::this_thread::get_id() << " : 1234567890abcdefghijklmnopqrstuvwxyz" << endl;
  41. sleep(1);
  42. cout << i << ":" << std::this_thread::get_id() << " : 1234567890abcdefghijklmnopqrstuvwxyz" << endl;
  43. // fl->unlock();
  44. sleep(1);
  45. i++;
  46. }
  47. }
  48. int main(int argc, char *argv[])
  49. {
  50. try
  51. {
  52. TC_FileMutex sl;
  53. sl.init("./test.lock");
  54. pthread_t itid1;
  55. pthread_t itid2;
  56. pthread_create(&itid1, NULL, (void *(*)(void *))&ThreadEntry1, (void*)&sl);
  57. pthread_create(&itid2, NULL, (void *(*)(void *))&ThreadEntry2, (void*)&sl);
  58. pthread_join(itid1, NULL);
  59. pthread_join(itid2, NULL);
  60. }
  61. catch(exception &ex)
  62. {
  63. cout << ex.what() << endl;
  64. }
  65. return 0;
  66. }