<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>RasterGrid Blog &#187; multithreading</title>
	<atom:link href="http://rastergrid.com/blog/tag/multithreading/feed/" rel="self" type="application/rss+xml" />
	<link>http://rastergrid.com/blog</link>
	<description>A technical blog from Daniel Rákos (aka aqnuep)</description>
	<lastBuildDate>Fri, 24 Feb 2012 03:23:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Synchronizable objects for C++</title>
		<link>http://rastergrid.com/blog/2010/02/synchronizable-objects-for-c/</link>
		<comments>http://rastergrid.com/blog/2010/02/synchronizable-objects-for-c/#comments</comments>
		<pubDate>Tue, 02 Feb 2010 19:01:56 +0000</pubDate>
		<dc:creator>Daniel Rákos</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Multiprocessing]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Samples]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[lock]]></category>
		<category><![CDATA[macro]]></category>
		<category><![CDATA[multithreading]]></category>
		<category><![CDATA[mutex]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[OpenMP]]></category>
		<category><![CDATA[synchronization]]></category>

		<guid isPermaLink="false">http://rastergrid.com/blog/?p=120</guid>
		<description><![CDATA[Previously I talked about how one can easily take advantage of multiprocessing using OpenMP. Even if the C pragmas introduced by the parallel programming API standard is very straightforward for simple programs, it simply doesn&#8217;t fit nicely in a complex C++ application that is built from the ground with the OOP in mind. To smoothly]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Frastergrid.com%252Fblog%252F2010%252F02%252Fsynchronizable-objects-for-c%252F%22%2C%20%22shorturl%22%3A%20%22http%3A%2F%2Fbit.ly%2FbbpIPT%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Synchronizable%20objects%20for%20C%2B%2B%22%20%7D);"></div>
<p>Previously I talked about how one can easily take advantage of multiprocessing using OpenMP. Even if the C pragmas introduced by the parallel programming API standard is very straightforward for simple programs, it simply doesn&#8217;t fit nicely in a complex C++ application that is built from the ground with the OOP in mind. To smoothly introduce OpenMP into such projects one need higher level constructs that hide the actual implementation details. This is the first article of a series that will try to provide reference implementations of such an abstraction. First, we will start with synchronizable primitives that try to reflect the functionality provided by the &#8220;synchronized&#8221; statement of Java.</p>
<p><span id="more-120"></span>This article is highly inspired by an article written by <a title="A &quot;synchronized&quot; statement for C++ like in Java" href="http://www.codeproject.com/KB/threads/cppsyncstm.aspx" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.codeproject.com/KB/threads/cppsyncstm.aspx?referer=');">Achilleas Margaritis</a><span style="line-height: normal; -webkit-border-horizontal-spacing: 5px; -webkit-border-vertical-spacing: 5px; font-size: small;"> and is mostly equivalent with his thoughts. My article tries to provide a portable reference implementation of a slightly modified version of the trick presented by Margaritis that uses OpenMP as the multiprocessing API back-end.</span></p>
<h2>Motivation</h2>
<p><span style="line-height: normal; -webkit-border-horizontal-spacing: 5px; -webkit-border-vertical-spacing: 5px; font-size: small;">According to the OO paradigm, classes and consequently objects provide an abstract interface to the underlying internal data or services of the modeled entity or entity class. When it comes to parallel programing we should provide facilities to enable concurrent access to shared resources that are in this case objects. Using plain OpenMP can be satisfactory, however when used extensively the OpenMP pragmas and API function calls introduced can greatly affect the readability and the maintainability of the code. Nevertheless, there can be platforms that use other APIs for handling race conditions. It is obvious that we need to encapsulate these facilities and provide an abstract tool-set instead.</span></p>
<h2>Implementation</h2>
<p><span style="line-height: normal; -webkit-border-horizontal-spacing: 5px; -webkit-border-vertical-spacing: 5px; font-size: small;">The very first building block of such a framework can be a mutex class that provides mutually exclusive access to certain resources. In the world of OpenMP this should look like something similar to the following:</span></p>
<pre class="brush: cpp">class Mutex {
public:
    Mutex() { omp_init_lock(&amp;_mutex); }
    ~Mutex() { omp_destroy_lock(&amp;_mutex); }
    void lock() { omp_set_lock(&amp;_mutex); }
    void unlock() { omp_unset_lock(&amp;_mutex); }
private:
    omp_lock_t _mutex;
};</pre>
<p>This seems already enough for us to make our Java-like &#8220;synchronized&#8221; statement, however we would like to create a framework that makes usage as easy and safe as possible. In order to get closer to this goal we apply the RAII (Resource Acquisition Is Initialization) design pattern to create our lock class:</p>
<pre class="brush: cpp">class Lock {
public:
    Lock(Mutex&amp; mutex) : _mutex(mutex), _release(false) { _mutex.lock(); }
    ~Lock() { _mutex.unlock(); }
    bool operator() const { return !_release; }
    void release() { _release = true; }
private:
    Mutex&amp; _mutex;
    bool _release;
};</pre>
<p>Our goal is to provide an inheritable interface for such objects that needs synchronization. However, this step has to involve severe considerations regarding to the provided interface as we explicitly need to conform to the following requirements:</p>
<ul>
<li>The interface shall not expose the interface of the underlying synchronization primitive, in our case the mutex class methods.</li>
<li>The interface shall be available only to the synchronizable objects but not for the external world as we would like to not just hide the implementation details of our abstract entity but also prevent the users to synchronize our objects as it should be the responsibility of the object itself.</li>
<li>The interface shall expose methods which are less prone to name collision, for convenience.</li>
</ul>
<p>If we take care of the presented conventions we end up with an interface similar to the following:</p>
<pre class="brush: cpp">class Synchronizable: protected Mutex {
protected:
	void enterSyncBlock() { this-&gt;lock(); }
	void exitSyncBlock() { this-&gt;unlock(); }
};</pre>
<p>Now we are almost at the finish line. We just need to inherit this class in order to have the needed facilities for an object that needs synchronization. However, using this interface directly is not the most comfortable and safe. If we would like to have a Java-like &#8220;synchronized&#8221; statement we have to call for additional help. Fortunately, we have our not so well respected C macro language coming to rescue us as we can use it to make some pseudo-language extensions. The simplest way to define our new statement is using the following line:</p>
<pre class="brush: cpp">#define synchronized(obj)  for(Lock obj##_lock = *obj; obj##_lock; obj##_lock.release())</pre>
<p>From now, we can really use object synchronization in C++ as easy as in Java, we just need the following syntax in the method of our shared objects:</p>
<pre class="brush: cpp">synchronized(this) {
    // some code that needs synchronization
}</pre>
<p>Now it is clearly visible how handy the RAII pattern became in our case. Beside that it is now very straightforward to use this statement it provides additional benefits:</p>
<ul>
<li>It makes the code more readable and as a result it is easier to maintain.</li>
<li>No need to call inconveniently named methods and use lock variables.</li>
<li>The synchronized code has it&#8217;s own scope inside the code.</li>
<li>It is exception-safe as the mutex is unlocked upon destruction.</li>
</ul>
<p>Additionally, we can also take advantage of the inherent problem in C++ regarding to multiple inheritance. If we inherit our object from other two synchronized objects then using a simple type casting we can explicitly specify which ancestor we would like to synchronize in a particular block. Also, to ease this we can define our synchronization statement instead of the Java-like one using the following line:</p>
<pre class="brush: cpp">#define synchronized(cls)  for(Lock obj##_lock = *static_cast&lt;cls*&gt;(this); obj##_lock; obj##_lock.release())</pre>
<p>In this case we pass the class name instead of the object pointer <em>this</em>. Using this later construct we can easily specify the correct ancestor that we would like to synchronize in case when we deal with multiple inheritance situations. Personally I prefer the later syntax as it is much more customized for C++ use cases.</p>
<p>As from now we don&#8217;t need a direct interface for entering and exiting our synchronization block we can simplify our synchronizable interface to the following chunk:</p>
<pre class="brush: cpp">class Synchronizable: protected Mutex {
};</pre>
<p>This is enough from now to provide the facilities needed for a synchronization block but still complies to the requirement that we would like to hide the synchronization primitive related details.</p>
<p>Beside this, Jörg came up with the idea today to replace the for loop in our macro with a single if statement. This seems reasonable as we don&#8217;t have to sacrifice any scoping and safety related benefits of our framework. This simplifies our lock class to the following:</p>
<pre class="brush: cpp">class Lock {
public:
    Lock(Mutex&amp; mutex) : _mutex(mutex) { _mutex.lock(); }
    ~Lock() { _mutex.unlock(); }
    bool operator() const { return true; }
private:
    Mutex&amp; _mutex;
};</pre>
<p>This definition of the lock class is satisfactory if we redefine our synchronized macro to use an if statement instead:</p>
<pre class="brush: cpp">/* Java-like synchronized statement */
#define synchronized(obj)  if (Lock obj##_lock = *obj)
/* alternative synchronized statement to support multiple inheritance */
#define synchronized(cls)  if (Lock obj##_lock = *static_cast&lt;cls*&gt;(this))</pre>
<p>Thanks to the useful comments we even managed to further optimize and minimize the support code needed for our new pseudo-language extension.</p>
<h2>Conclusion</h2>
<p>We have seen an example how one can implement an easy to use synchronizable interface for C++. Also, we&#8217;ve provided a concrete implementation that is based on OpenMP. This library is still far from an API that provides all the necessary constructs that one needs for using parallel programming in their C++ projects, however we made our first step and I will recap on the subject in subsequent articles to further extend this framework.</p>
<p>Credits go to Achilleas Margaritis whose article inspired me to write mine and to Jörg for the useful improvement ideas.</p>
<h3>Full source code</h3>
<p><strong>Language:</strong> C++<br />
<strong> Platform:</strong> cross-platform<br />
<strong> Dependency:</strong> OpenMP<br />
<strong> Download link:</strong> <a title="omp_sync.h" href="/blog/wp-content/uploads/2010/02/files/omp_sync.h" target="_blank">omp_sync.h</a><br />
<strong> Comments:</strong> In order to use it as it is, you will need a C++ compiler supporting OpenMP like GCC 4.2 or Visual C++ 2008.</p>

]]></content:encoded>
			<wfw:commentRss>http://rastergrid.com/blog/2010/02/synchronizable-objects-for-c/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Flawless alternative to SDL</title>
		<link>http://rastergrid.com/blog/2010/01/flawless-alternative-to-sdl/</link>
		<comments>http://rastergrid.com/blog/2010/01/flawless-alternative-to-sdl/#comments</comments>
		<pubDate>Wed, 27 Jan 2010 19:47:01 +0000</pubDate>
		<dc:creator>Daniel Rákos</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[GLFW]]></category>
		<category><![CDATA[multimedia]]></category>
		<category><![CDATA[multithreading]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[OpenAL]]></category>
		<category><![CDATA[OpenGL]]></category>
		<category><![CDATA[SDL]]></category>
		<category><![CDATA[SFML]]></category>

		<guid isPermaLink="false">http://rastergrid.com/blog/?p=108</guid>
		<description><![CDATA[There was always big need for libraries that provide an abstract interface towards the basic platform specific facilities that are necessary for setting up an execution environment for a particular application. In the OpenGL world one of the first such libraries was GLUT. After a while more and more functionalities were put into these libraries]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Frastergrid.com%252Fblog%252F2010%252F01%252Fflawless-alternative-to-sdl%252F%22%2C%20%22shorturl%22%3A%20%22http%3A%2F%2Fbit.ly%2FaXVqCz%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Flawless%20alternative%20to%20SDL%22%20%7D);"></div>
<p>There was always big need for libraries that provide an abstract interface towards the basic platform specific facilities that are necessary for setting up an execution environment for a particular application. In the OpenGL world one of the first such libraries was GLUT. After a while more and more functionalities were put into these libraries that reflect more or less the requirements of application developers. One such framework is SDL. It seems that SDL is still the most respected one of these and it is preferred by the developer community. However, in this topic I will present an alternative that proved its superiority to me in the last few months&#8230;<br />
<span id="more-108"></span><img title="More..." src="http://rastergrid.com/blog/wp-includes/js/tinymce/plugins/wordpress/img/trans.gif" alt="" /></p>
<h2>Why would I need such a library?</h2>
<p>There are loads of reasons why it is good to have such a framework in your toolkit. I would like to present only a few that I consider important. First of all, having some easy to use API to setup the basic environment for your application, like a window with an OpenGL rendering context, simply removes the burden from dealing with such platform specific details and concentrate on the actual product. Next, they usually give a quite good degree of platform portability so you don&#8217;t have to study specific operating system APIs and you can still deploy your application on multiple platforms. I can recite many other reasons but the most important one is that they are reusable components so you don&#8217;t reinvent the wheel.</p>
<p>For a while I was quite satisfied with my own implementation of such a toolkit until I moved from Delphi to C++ development. This forced me to look around on the market to find a replacement for my proprietary solution as C++ has a very large developer community so it shouldn&#8217;t be that hard to find a suitable framework. Well, actually this wasn&#8217;t the case as it was the time when the OpenGL 3 specification came out with its new context creation and deprecation model. It was very embarrassing to observe that even the most popular multimedia frameworks are hardly adopting these new features.</p>
<p>At that time I realized that my library choice will heavily affect my productivity in the future so I have to think well which one I will use afterwards. To ease the selection I created something like a wish-list about what I expect from such a library. The most important issues were the following:</p>
<ul>
<li>Feature-rich - The library must provide the most basic functionalities needed for an average OpenGL application. This includes window and rendering context handling, keyboard and mouse user input capture, timing facilities and, of course, supports OpenGL 3 contexts. Optionally it would be nice if the API also provides multi-threading, image and audio handling, basic network operations, joystick support, etc.</li>
<li>Modular - The library must be modular, that means I can select which components of the framework I would like to use in a particular application. Sometimes less is more so, as an example, in a very simple cube rotating OpenGL demo I don&#8217;t want to link against a library which contains network handling. Such monolithic libraries makes life much harder as they usually rely on exotic dependencies and prevent easy deployment of the application.</li>
<li>Portable - It should be portable, at least it should work on the three most popular PC platforms: Windows, Linux and MacOSX. It has to work also with a variety of build systems, preferably with Visual C++, GCC and Xcode. Optionally it would be nice if it can be interfaced by applications written in other programming languages than C/C++.</li>
<li>Easy to use - In an ideal world such a framework should have a very clean interface and its usage must be very natural for the developer. This issue is however rather subjective so what it easy to use for one developer maybe it&#8217;s not the best for another. Regarding to this issue I will present the alternatives, obviously, from my perspective.</li>
</ul>
<p>Maybe choosing such a multimedia library for an OpenGL hobby project is just a matter of taste, but when it comes to support for OpenGL 3 context support, developers have very limited choices and one most probably faces decisions when they have to make some trade-offs when selecting any of  these libraries. Anyway, as one of my key requirements is that the library must support OpenGL 3 contexts, it is not that difficult to present all the most popular alternatives.</p>
<h2>Simple DirectMedia Layer</h2>
<p>SDL has a long history in this domain and it proved that it is an excellent choice for most hobbyists and even for professionals. It has been used in tons of different free and commercial applications and it is probably still the most preferred library in this category. Lets examine it regarding to the issues presented previously.</p>
<p>SDL provides almost all the facilities that are needed for an average graphics application. Together with some additional libraries developed as an extension to SDL like SDL_image and SDL_net it conforms to almost all of my requirements regarding to feature content. The most important is that its latest development branch also has support for OpenGL 3.</p>
<p>From point of view of modularity, especially taking into account that the less common used facilities are provided by different add-ons, SDL seems to be a good choice. However, the SDL core itself has already a bit too much dependencies on other operating system specific libraries, especially the reliance on DirectX on the Windows platform. Even if probably most of you can live with this, it is simply unacceptable for me. Anyway, this is still not the biggest problem what I&#8217;ve faced with when I checked out whether SDL suites my needs.</p>
<p>Platform portability is one of the key advantages of SDL as it even supports many other platforms than what was on my wish-list. Also regarding to language portability, the C interface of SDL makes it very easy to drop into a Delphi project as an example. Actually there are also plenty of  bindings for other languages for interfacing SDL including but not limited to Java, C#, Delphi, Ada, Perl and python. However, when it comes to build system portability I have to mention my bad experiences.</p>
<p>First of all I am that kind of animal who uses GCC also for compilations under Windows. As SDL comes with an automake based build system which proved to be unusable using MSYS and I would rather not use Cygwin as it also introduces quite many unwanted external dependencies. After giving up compilation using MinGW, I tried to build the library using the good old Visual C++ IDE. This is when I faced the problem that I would have to install the DirectX SDK in order to compile SDL. The final hit was that even after downloading and installing the huge DirectX SDK, SDL still refused to compile with weird compiler errors.</p>
<p>By the way, all these compilation related issues wouldn&#8217;t be a problem for me if SDL would come with a binary release. Even if it has such releases for earlier versions, it does not have it for the latest development branch which contains the OpenGL 3 related stuff. So actually I cannot even prove that the OpenGL 3 specific implementation in SDL works in practice or not.</p>
<p>The API interface provided by SDL got skewed up meanwhile, arising from the fact that SDL has a long history, but still I cannot say that the interface is not clean enough to be easily used in any project. So in this regard SDL is still a major player.</p>
<h2>The OpenGL Framework</h2>
<p>My second was GLFW as it was the only library that supported OpenGL 3 as far as I knew at that time. For those who are not familiar with this library, GLFW is a simple yet powerful toolkit with a similar interface like GLUT but with added capabilities like multi-threading and joystick support (see <a title="GLFW Home Page" href="http://glfw.sourceforge.net/" target="_blank" onclick="pageTracker._trackPageview('/outgoing/glfw.sourceforge.net/?referer=');">GLFW home page</a>).</p>
<p>It is a very feature-rich framework compared to its size and even not being very modular, it still does not involve that much external dependencies as SDL. As it also provides OpenGL 3 support only in it&#8217;s latest development branch I had to compile the code here as well, however, it was straightforward to do it even using MinGW so I don&#8217;t have any complains regarding to this subject. Also it supports multiple platforms, at least those that I am mainly interested in.</p>
<p>Unfortunately, as many other early OpenGL 3 context handling implementations, it wasn&#8217;t working on all platforms. More precisely, under Windows the OpenGL 3 code in the development at that time (about half year ago) worked only with NVIDIA cards as, non-compatible with the Microsoft WGL specification, NVIDIA&#8217;s ICD exposed the wglCreateContextAttribARB function even if there was no valid OpenGL context bound and, as usual, the developers used only NVIDIA cards for testing which resulted in a partially working OpenGL 3 context handling implementation.</p>
<p>As the code of GLFW is also very straightforward and handy to read, I easily corrected the bug in the OpenGL 3 context handling and I used GLFW for a few months for my hobby projects. After a while, however, the lack of some facilities in GLFW made me to think through this library selection again as I didn&#8217;t want to end up using several different libraries for different purposes which would result in a barely well designed code structure.</p>
<h2>Simple and Fast Multimedia Library</h2>
<p>We&#8217;ve arrived to the main topic of this article. Finally I&#8217;ve found SFML which at first sight seemed to be &#8220;just another multimedia library&#8221; but I soon realized that it&#8217;s far more than that.</p>
<p>First of all, it has all the features I needed. Beside the basic ones, it has very nice support for networking but not just basic socket programming using TCP or UDP packets, but a more comprehensive toolkit for even HTTP and FTP transactions. It also has built-in sound support via OpenAL which was another thing that caught my attention as I also preferred OpenAL over other audio libraries like fmod. Beside this, it has many other interesting features but you&#8217;d better check out the <a title="SFML Home Page" href="http://www.sfml-dev.org/" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.sfml-dev.org/?referer=');">SFML project site</a>.</p>
<p>As I already got used to, SFML had also support for OpenGL 3 context handling but only in the latest development branch. Anyway, this seemed to be no problem as I had no building issues like that what I met in case of SDL. What is more important that the OpenGL 3 implementation actually worked flawlessly, there was no need for any modification. Just to demonstrate, setting up an OpenGL 3 window with SFML can be as easy as writing the following line of code:</p>
<pre class="brush: cpp">sf::Window App(sf::VideoMode(800, 600, 32), "OpenGL 3 window", sf::Style::Close, sf::ContextSettings(24, 8, 0, 3, 2));</pre>
<p>When it comes to modularity, SFML also wins at me. First, it does not need any exotic libraries or headers for rebuilding the framework. Beside this, it has minimal number of external dependencies but only to the operating system libraries used. It is also modular as different sub-systems of the framework are compiled into different library modules so in your project you can simply select which ones do you intend to use to further minimize deployment issues.</p>
<p>From portability point of view, SFML supports all the platforms that are important for me. Also SFML works with no fuss indifferent with all the compiler tool-chains I&#8217;ve tried. At first sight I had concerns regarding to the language portability of SFML as is was written in C++ and this C++ interface is exposed to the client. However, this issue was solved by the library by providing a C wrapper called CSFML together with the framework itself which makes it rather straightforward to write binding for virtually any programming language.</p>
<h2>Conclusion</h2>
<p>If I haven&#8217;t convinced you so far that SFML can be the perfect choice as a multimedia library for almost any hobby or commercial product then you should check out the full feature list and see for yourself. I will probably write more about SFML in the future and you will also meet some usage examples in my upcoming demos.</p>
<p>If you are not interested in the additional features provided by SFML, instead you are just searching for a very basic framework that provides you a window and some user input handling then GLFW can be your choice. However, based on my bad experiences I would not advise anymore the usage of SDL to anybody but maybe I&#8217;m a bit too inclement.</p>

]]></content:encoded>
			<wfw:commentRss>http://rastergrid.com/blog/2010/01/flawless-alternative-to-sdl/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

