File: test_5502.cpp

package info (click to toggle)
boost1.83 1.83.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 545,632 kB
  • sloc: cpp: 3,857,086; xml: 125,552; ansic: 34,414; python: 25,887; asm: 5,276; sh: 4,799; ada: 1,681; makefile: 1,629; perl: 1,212; pascal: 1,139; sql: 810; yacc: 478; ruby: 102; lisp: 24; csh: 6
file content (93 lines) | stat: -rw-r--r-- 1,825 bytes parent folder | download | duplicates (15)
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright (C) 2010 Vicente Botet
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

// bm.cpp

//  g++ test.cpp -lboost_thread-mt && ./a.out

// the ration of XXX and YYY determines
// if this works or deadlocks
int XXX = 20;
int YYY = 10;

#include <boost/thread/thread_only.hpp>
#include <boost/thread/shared_mutex.hpp>

//#include <unistd.h>
#include <iostream>
#include <boost/detail/lightweight_test.hpp>

using namespace std;

//void sleepmillis(useconds_t miliis)
void sleepmillis(int miliis)
{
  //usleep(miliis * 1000);
  boost::this_thread::sleep(boost::posix_time::milliseconds(miliis));
}

void worker1(boost::shared_mutex * lk, int * x)
{
  (*x)++; // 1
  cout << "lock b try " << *x << endl;
  while (1)
  {
    if (lk->timed_lock(boost::posix_time::milliseconds(XXX))) break;
    sleepmillis(YYY);
  }
  cout << "lock b got " << *x << endl;
  (*x)++; // 2
  lk->unlock();
}

void worker2(boost::shared_mutex * lk, int * x)
{
  cout << "lock c try" << endl;
  lk->lock_shared();
  (*x)++;
  cout << "lock c got" << endl;
  lk->unlock_shared();
  cout << "lock c unlocked" << endl;
  (*x)++;
}

int main()
{

  // create
  boost::shared_mutex* lk = new boost::shared_mutex();

  // read lock
  cout << "lock a" << endl;
  lk->lock_shared();

  int x1 = 0;
  boost::thread t1(boost::bind(worker1, lk, &x1));
  while (!x1)
    ;
  BOOST_TEST(x1 == 1);
  sleepmillis(500);
  BOOST_TEST(x1 == 1);

  int x2 = 0;
  boost::thread t2(boost::bind(worker2, lk, &x2));
  t2.join();
  BOOST_TEST(x2 == 2);

  lk->unlock_shared();
  cout << "unlock a" << endl;

  for (int i = 0; i < 2000; i++)
  {
    if (x1 == 2) break;
    sleepmillis(10);
  }

  BOOST_TEST(x1 == 2);
  t1.join();
  delete lk;

  return 0;
}