Ticket #5847: sp-test.cpp

File sp-test.cpp, 2.1 KB (added by Jeffrey Walton <noloader@…>, 11 years ago)

Test program

Line 
1// g++ -g3 -ggdb -O0 -D_REENTRANT=1 sp-test.cpp -o sp-test.exe -lpthread
2
3#include <iostream>
4using std::cout;
5using std::cerr;
6using std::endl;
7using std::ostream;
8
9#include <string>
10using std::string;
11
12#include <vector>
13using std::vector;
14
15#include <sstream>
16using std::stringstream;
17using std::istringstream;
18using std::ostringstream;
19
20#include <boost/shared_ptr.hpp>
21using boost::shared_ptr;
22
23#include <stdlib.h>
24#include <error.h>
25#include <errno.h>
26#include <pthread.h>
27#include <string.h>
28
29#if !defined(nullptr_t)
30# define nullptr NULL
31#endif
32
33#if !defined(byte)
34typedef unsigned char byte;
35#endif
36
37struct Block
38{
39 explicit Block() { }
40 virtual ~Block() { }
41 byte block[24];
42};
43
44static const unsigned int THREAD_COUNT = 128;
45static const unsigned int ITERATIONS = 2048;
46
47void* WorkerThreadProc(void* param);
48void Message(ostream& strm, const string& msg);
49
50typedef shared_ptr<Block> BlockPtr;
51
52static const unsigned int SIZE = 128;
53BlockPtr blocks[SIZE];
54
55int main(int, char**)
56{
57 srand(0);
58
59 pthread_t threads[THREAD_COUNT];
60
61 // *** Worker Threads ***
62 for(unsigned int i=0; i<THREAD_COUNT; i++)
63 {
64 int ret = pthread_create(&threads[i], nullptr, WorkerThreadProc, (void*)i);
65 if(0 != ret /*success*/)
66 {
67 ostringstream oss;
68 oss << "pthread_create failed (thread " << i << "): " << strerror(errno);
69 Message(cerr, oss.str());
70 }
71 }
72
73 for(unsigned int i=0; i<THREAD_COUNT; i++)
74 {
75 int ret = pthread_join(threads[i], nullptr);
76 if(0 != ret /*success*/)
77 {
78 ostringstream oss;
79 oss << "pthread_join failed (thread " << i << "): " << strerror(errno);
80 Message(cerr, oss.str());
81 }
82 }
83}
84
85void* WorkerThreadProc(void* param)
86{
87
88 // give up the remainder of this time quantum to help
89 // interleave thread creation and execution
90 sleep(0);
91
92 for(unsigned int i = 0; i < ITERATIONS; i++)
93 {
94 int idx1 = rand() % SIZE;
95 int idx2 = rand() % SIZE;
96
97 blocks[idx1] = blocks[idx2];
98 }
99
100 return (void*)0;
101}
102
103void Message(ostream& strm, const string& msg)
104{
105
106}
107