U++ framework
Do not panic. Ask here before giving up.

Home » U++ Library support » U++ MT-multithreading and servers » Simple class to handle variables used by different threads
Re: Simple class to handle variables used by different threads [message #45040 is a reply to message #45026] Sun, 23 August 2015 20:34 Go to previous messageGo to previous message
mirek is currently offline  mirek
Messages: 14291
Registered: November 2005
Ultimate Member
koldo wrote on Fri, 21 August 2015 13:41
Hello all

I wanted to ask you if this class could serve to manage variables that may be read and changed from different threads
template <class T>
class threadSafe {
public:
	threadSafe() 		{}
	threadSafe(T v) 	{val = v;}
	void operator=(T v)	{BarrierWrite(val, v);}
	operator T() 		{return ReadWithBarrier(val);}
   
private:
	volatile T val;
};

It can be used as simple as this:
threadSafe<int> val = 23;
double d = val + 3.5;


Other sample in two threads:
// Main thread
threadSafe<bool> thread1Busy;

// Thread 1
thread1Busy = true;
...
thread1Busy = false;

// Thread 2
...
while (thread1Busy)
	Sleep(100);
...


I would be quite worried about

threadSafe<int> x;

x = x + 1;


Also, I am not quite sure that barriers are used correctly here.. What are they supposed to do?

BTW, second example would work fine without any synchronization at all...

Mirek
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: How to just Post data ?
Next Topic: Mt.cpp broken compile using 9604 nightly snap-shot
Goto Forum:
  


Current Time: Sat Jul 04 10:13:23 GMT+2 2026

Total time taken to generate the page: 0.00684 seconds