Overview
Examples
Screenshots
Comparisons
Applications
Download
Documentation
Tutorials
Bazaar
Status & Roadmap
FAQ
Authors & License
Forums
Funding Ultimate++
Search on this site
Search in forums












SourceForge.net Logo
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: 13975
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: Mon Apr 29 08:46:54 CEST 2024

Total time taken to generate the page: 0.03232 seconds