1 | //
|
---|
2 | // Concurrently streaming ptime to a std::ostringstream crashes under MinGW-32.
|
---|
3 | // http://jc-bell.com
|
---|
4 | //
|
---|
5 | #include <boost/date_time/posix_time/posix_time.hpp>
|
---|
6 | #include <boost/thread.hpp>
|
---|
7 | #include <sstream>
|
---|
8 | #include <cstdlib>
|
---|
9 |
|
---|
10 | #include <iostream>
|
---|
11 |
|
---|
12 |
|
---|
13 | namespace P = boost::posix_time;
|
---|
14 | namespace T = boost::this_thread;
|
---|
15 |
|
---|
16 | typedef P::ptime ptime;
|
---|
17 | typedef boost::mutex::scoped_lock scoped_lock;
|
---|
18 |
|
---|
19 | boost::mutex ioLock;
|
---|
20 |
|
---|
21 | ptime LocalTime()
|
---|
22 | {
|
---|
23 | return P::microsec_clock::local_time();
|
---|
24 | }
|
---|
25 |
|
---|
26 |
|
---|
27 | void ThisCrashes()
|
---|
28 | {
|
---|
29 | static boost::mutex myLock;
|
---|
30 |
|
---|
31 | ptime nowPT = LocalTime();
|
---|
32 |
|
---|
33 | // Wrap even the ostringstream in a lock and it works.
|
---|
34 | //scoped_lock lk(myLock);
|
---|
35 |
|
---|
36 | std::ostringstream oss; // local to this function.
|
---|
37 |
|
---|
38 | // Wrap just the ostream insertion in a mutex and it works better, but still crashes.
|
---|
39 | //scoped_lock lk(myLock);
|
---|
40 | // The following line is the culprit. Comment it out and no crash.
|
---|
41 | oss << nowPT << "; " << nowPT;
|
---|
42 | //lk.unlock();
|
---|
43 |
|
---|
44 | std::string other = oss.str();
|
---|
45 | }
|
---|
46 |
|
---|
47 |
|
---|
48 | int GetRand(int maxRand)
|
---|
49 | {
|
---|
50 | std::size_t r = std::rand();
|
---|
51 | return (r * maxRand) / RAND_MAX;
|
---|
52 | }
|
---|
53 |
|
---|
54 |
|
---|
55 | void CrasherThread()
|
---|
56 | {
|
---|
57 | ptime endTime = LocalTime() + P::seconds(300);
|
---|
58 | int iterCount = 0;
|
---|
59 | while (LocalTime() < endTime) // iterCount < 1000) //
|
---|
60 | {
|
---|
61 | T::sleep(P::milliseconds(GetRand(100)));
|
---|
62 | ++iterCount;
|
---|
63 | if ((iterCount % 50) == 0)
|
---|
64 | {
|
---|
65 | scoped_lock lk(ioLock);
|
---|
66 | std::cout << "Thread " << T::get_id() << " " << iterCount << std::endl;
|
---|
67 | }
|
---|
68 | ThisCrashes();
|
---|
69 | }
|
---|
70 |
|
---|
71 | scoped_lock lk(ioLock);
|
---|
72 | std::cout << "Thread " << T::get_id() << " done: " << iterCount << std::endl;
|
---|
73 | }
|
---|
74 |
|
---|
75 |
|
---|
76 | int main(int argc, char *argv[])
|
---|
77 | {
|
---|
78 | std::cout << "Starting..." << std::endl;
|
---|
79 |
|
---|
80 | boost::thread_group tg;
|
---|
81 |
|
---|
82 | // Make just one thread and it works.
|
---|
83 | for (int i = 0; i < 10; ++i)
|
---|
84 | tg.create_thread(CrasherThread);
|
---|
85 |
|
---|
86 | tg.join_all();
|
---|
87 | std::cout << "Exiting normally..." << std::endl;
|
---|
88 | return 0;
|
---|
89 | }
|
---|
90 |
|
---|