Salve,

sto creando una piccola applicazione basata sugli eventi per fare in modo che il thread principale Producer e vari threads Consumer comunichino tra di loro l'accesso ad una area di memoria condivisa. Il compito dei threads Consumer è di registrare la loro presenza (il loro buffer + il loro HANDLE) dentro a delle mappe con chiave unica data da: GetCurrentThreadId().

Tuttavia, i vari thread fanno uso di una sola mappa (std::map) con scope globale. Quindi è necessario implementare una mutua esclusione.

Mi è stato consigliato dapprima di usare boost::mutex (anche perchè portabile) e poi i vari mutex forniti dalla piattaforma win32. Ma alla fine mi è stato consigliato di preferire la sezione critica di win32 ovvero: CRITICAL_SECTION

Essendo per me una cosa nuova non saprei come implementarla nel mio progetto, per questo vi posto un codice di esempio che replica in breve lo scenario che mi trovo ad affrontare:

codice:
// Buffer structs "circular"

struct buffer
{
    unsigned char data[1024];   // binary data container
    int bytesRecorded;          // bytes actually written (to read)
    int flag;                   // Empty/filled (enum)
    buffer(...);                // constructor()
}; 

struct circular
{
    circular_buffer<buffer> cb; // Cicular buffer based on "buffer"
};

// Global maps

map<int, circular> users;
map<int, circular>::iterator uit;
map<int, HANDLE> eventi; 

int main()
{
	// TODO: launch Producer thread.
	(...)

	// TODO: Set up server and accept incoming
	// requests. Each time a client connects
	// spawn a new Consumer thread
	(...)

	return 0; // never for the moment!
}

// Thread Consumer is launched
// anytime a client conencts.

thread Consumer
{
	int threadid = (int)GetCurrentThreadId();

    	// Create event & push it in the "eventi" map
	//
    	HANDLE hevent = CreateEvent(NULL,0,0,NULL);
    	eventi.insert(make_pair(threadid, hevent));

	// Prepare & add circular buffer to the "users" map
	//
    	circular c; 
	users.insert(make_pair(threadid, c)); 

	// Loop...
	//
	while(1)
	{
		// Callback event
		WaitForSingleObject(eventi[threadid], INFINITE); 

		// TODO: read buffer from "users" map
		// and send it to the client. If the
		// client disconnect break the while loop
	}

 	// Close & remove event from event map
	//
    	CloseHandle(eventi[threadid]);
    	eventi.erase(threadid);

	// Remove buffer from the map
	//
	users.erase(threadid);

	return 0;
}

// Thread Producer is launched
// once. Its main goal is to write
// the same data to all the Consumer
// threads.

thread Producer
{
	while(1)
	{
		// TODO: write on every
		// element of map "users"
		//
		for(uit=users.begin(); uit!=users.end(); ++uit)
		{
			users[uit->first].cb.push_back(buffer(...));

			// Signal event in the Cosumer
			// thread (buffer written).
			//
			if(eventi[uit->first])
            			SetEvent(eventi[uit->first]); 
		}
	}
	return 0;
}
come potrei implementare l'uso della CRITICAL_SECTION ??

grazie