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
| #include <windows.h>
#include <cstdio>
template< typename T >
class MiniVector
{
private:
size_t m_size;
T m_value[12];
public:
MiniVector() :
m_size(0),
m_value()
{
}
void push_back(const T& value)
{
m_value[m_size++] = value;
}
void pop_back()
{
m_size--;
}
const T& at(size_t index) const
{
return m_value[index];
}
bool empty() const
{
return m_size == 0;
}
void push_back(const T& value) volatile
{
m_value[m_size++] = value;
}
void pop_back() volatile
{
m_size--;
}
const volatile T& at(size_t index) const volatile
{
return m_value[index];
}
bool empty() const volatile
{
return m_size == 0;
}
};
int thread1fun(volatile MiniVector<int>* vec)
{
vec->push_back(0);
printf("initial value : %d\n", vec->at(0));
vec->pop_back();
while(vec->empty()) /*wait*/;
printf("received an element : %d\n", vec->at(0));
return 0;
}
int thread2fun(MiniVector<int>* vec)
{
Sleep(1000);
printf("pushing an element\n");
vec->push_back(1);
return 0;
}
int main(int argc, char *argv[])
{
MiniVector<int> s_ListOfInt;
HANDLE thread1 = CreateThread( 0, 12000, (LPTHREAD_START_ROUTINE)thread1fun, &s_ListOfInt, 0, 0);
if(!thread1)
return 1;
HANDLE thread2 = CreateThread( 0, 12000, (LPTHREAD_START_ROUTINE)thread2fun, &s_ListOfInt, 0, 0);
if(! thread2)
return 1;
WaitForSingleObject(thread1,2000);
WaitForSingleObject(thread2,2000);
return 0;
} |
Partager