[Gc] Re: random problem in simple c++ program

Achilleas Margaritis axilmar at otenet.gr
Thu Dec 13 11:58:03 PST 2007



I've converted the program to use Win32 threads...but I still have the 
same problems.

Does the 7.0 multithreaded version work at all under Windows? should I 
revert to a previous version (6.8 for example?)

Here is the program:


#include <windows.h>
#include <gc.h>
#include <list>
using namespace std;


//number of allocations per thread
const int MAX_ALLOC = 1;


//critical section
class CriticalSection {
public:
     CriticalSection() {
         InitializeCriticalSection(&m_cr);
     }

     ~CriticalSection() {
         DeleteCriticalSection(&m_cr);
     }

     void lock() {
         EnterCriticalSection(&m_cr);
     }

     void unlock() {
         LeaveCriticalSection(&m_cr);
     }

private:
     CRITICAL_SECTION m_cr;
};


template <class T> class Lock {
public:
     Lock(T &o) : m_object(o) {
         m_object.lock();
     }

     ~Lock() {
         m_object.unlock();
     }

private:
     T &m_object;
};


//global mutex
CriticalSection cr;


//list of threads
list<DWORD> threads;


//synchronized add thread
void add_thread(DWORD handle) {
     Lock<CriticalSection> lock(cr);
     threads.push_back(handle);
}


//synchronized remove thread
void remove_thread(DWORD handle) {
     Lock<CriticalSection> lock(cr);
     threads.remove(handle);
}


//synchronized threads empty
bool threads_empty() {
     Lock<CriticalSection> lock(cr);
     return threads.empty();
}


//used for allocating random sizes
int rnd(int i) {
     return rand() % i;
}


//allocates memory
DWORD WINAPI allocatorThread(void *p) {
     DWORD thread = GetCurrentThreadId();
     add_thread(thread);

     printf("beginning allocator thread\n");

     //allocate memory
     for(int i = 0; i < MAX_ALLOC; ++i) {
         void *p = GC_MALLOC(10 + rnd(1000));
     }

     printf("ending allocator thread\n");

     //remove thread from list
     remove_thread(thread);
     return 0;
}


//the thread that spawns the allocator threads
DWORD WINAPI spawnerThread(void *p) {
     DWORD thread = GetCurrentThreadId();

     add_thread(thread);

     printf("beginning spawner thread\n");

     //create other threads
     for(int i = 0; i < 10; ++i) {
         GC_CreateThread(NULL, 0, allocatorThread, 0, 0, NULL);
     }

     printf("ending spawner thread\n");

     //remove the thread
     remove_thread(thread);
     return 0;
}


//cleanup; called at exit
void cleanup() {
     //periodically check if all threads have terminated
     while (!threads_empty()) {
         Sleep(1000);
     }
}


//main
int main() {
     //init the gc
     GC_INIT();

     //install an exit handler
     atexit(cleanup);

     //create and register the main thread
     GC_CreateThread(NULL, 0, spawnerThread, 0, 0, NULL);

     getchar();
     return 0;
}



More information about the Gc mailing list