Why creating objects inside constructors is a bad move

So recently I’ve started studying how to create multi-threaded applications and one of the problems I stumbled upon is the “this” reference escaping. What it means is that you pass the reference of an object that isn´t fully constructed to another piece of code in your application that will use that object. As with the majority of multi-threaded bugs, this can have subtle consequences ranging from all working fine to application crashes.

One of the easiest ways to show this problem is by creating new objects in the constructor. If we are not really carefull, we may let the this reference escape the constructor before this object is fully created. This causes problems because another thread may start using the object before the constructor completes. A simple example is creating a thread in the constructor like so:

public Xpto()
    list = new LinkedList<int>();
    new Thread(this.Get).Start();

public int Get()
    return list.GetFirst();

This way, the compiler may decide to reorder the two “instructions” and make the thread call the method this.Get() before the list is created.

Please note that the Thread.Start() has volatile properties meaning that everything related to the thread is garanteed to happen before it starts. However the thread only needs the “this” reference and dosen’t use the list directly. So from the point-of-view of the compiler, he is allowed to reorder the instructions as he pleases and so may decide that the call to the list constructor should occur AFTER the thread starts (since by this time the “this” reference already exists)!

Posted in Knowledge | Tagged , , , , , , , | 2 Comments

How to setup TivaWare in Code Composer Studio manually

The only steps needed are the following:

  1. Install TivaWare inside the “ti” folder.
  2. Go to View>Resource Explorer and import driverlib, grlib, sensorlib and usblib.
  3. Build the 3 projects.

Now, when creating a new project define the following symbols (Properties>Build>ARM Compiler>Advanced Options>Predefined Symbols):


The second symbol allows for calling ROM functions instead of normal functions when “rom.h” is included. Eg. ROM_GPIOPinWrite() instead of GPIOPinWrite()

Next is to tell the compiler where to find the header files. To do so, go to the project properties and navigate to: Build>ARM Compiler>Include options. Once there, click the top green “+” sign (right below the “Manage Configurations…” button) and then , in the new window, click “Browse…” and add the path to TivaWare install folder (tipicaly: C:\ti\TivaWare_C_Series-x.x.x.xxxxx).

Finally, we just need to tell the linker where to find the compiled TivaWare libraries: driverlib.lib, usblib.lib, sensor.lib and grlib.lib.

I’m going to exemplify adding the driverlib.lib in debug configuration only. To add the other libraries just follow the same steps.

To add the driverlib.lib go to the project properties and navigate to Build>ARM Linker>File Search Path, then click top green “+” sign (right below the “Manage Configurations…” button), click “Workspace” and finally navigate to “driverlib>Debug>driverlib.lib” and click “Ok”.

That’s it, now you can use the TivaWare library in your code!


PS: This is only for when building in debug mode. For building the release mode, just follow the steps after point number 3 but build the libraries in release mode, and on the last step,  go to the Release folder instead of the Debug folder and you are good to go.


Posted in Uncategorized | Leave a comment

Disabling Intel Adaptive Contrast Enhancement via registry

WARNING: Don’t do this unless you know what you are doing. Messing with the registry can break your computer!

NOTE: This is not related to Windows automatic brightness adjustment because that uses a light sensor, usually located near the keyboard.

This post is about disabling Intel’s Adaptive Contrast Enhancement. What ACE does is automatically adjust the contrast of your display whenever you are viewing a dark or light image or web page for example in order to make it easier on your eyes.

By the looks of this SO thread, the Intel apps don’t work so we need to do it the old fashioned way and edit the windows registry. To do this see the following steps:

  1. Open start menu/start screen and type “regedit” and press enter.
  2. Navigate to: HKEY_LOCAL_MACHINE\SOFTWARE\Intel\Display\igfxcui\Media
  3. Double click the key named “EnableACE”.
  4. Set its value to 0 in the “value data” field
  5. Press F5 to refresh the registry
  6. Reboot your computer.

After this, your Intel ACE should be completely disabled and no longer changing your displays contrast.

This should work in Windows 10 using Intel HD Graphics driver version



Posted in Knowledge | Leave a comment

Little MySQL optimization/weird behaviour

Here is another little weird behaviour about MySQL (5.5.46-0ubuntu0.14.04.2).

Today i needed to make a query for searching a table with millions of rows for all rows between two dates. The query goes something like this:

WHERE Tbl1.id=1 AND (date BETWEEN '2015-10-24T15:00:00+00:00' AND '2015-10-24T15:00:00+00:00')
LIMIT 1000

Running querys like this should be quick, even for millions of rows (with proper indexes obviously), however it was taking several minutes to get the rows.

So where is the problem? Well, you see that strange format for the dates? That is the default output for moment.js’s format(). I’ve been using it to get the start and end dates from the user.

The problem arises from the fact that MySQL does not support that particular date format string (not sure if MariaDB has the same problem) but the solution is simple. Call moment.js’s format() with the correct format string (in my case it was .format(“YYYY-MM-DD HH:mm”)) and all should be good again.

Now, the weird behaviour is that MySQL dosen’t really complain about the invalid date format. It will throw a warning about it (that you may not see if you are using PHP for executing the query, depending on the PDO configuration) but appart from that it will, oddly, return the correct results. It will just take a long time because it will throw a warning for each row that it scans while building the result set.

Posted in Knowledge | Tagged , , , | Leave a comment

Diference between GPIOPinConfigure() and GPIOPinTypeXXX()

When working with the tivaware lib, you need two functions to configure the GPIOs to work with a given peripheral:
GPIOPinConfigure() and GPIOPinTypeXXX()

Now the discription of those functions where i little confusing (at least to me) so here is my explanation of how they work:

GPIOPinConfigure() and GPIOPinTypeXXX() are two parts of the same thing.

GPIOPinConfigure() configures the pin mux that selects the peripheral function
associated with a particular GPIO pin. ONLY AFFECTS THE MUX AND NOTHING MORE.

GPIOPinTypeXXX() on the other hand, configures the GPIO pins with the needed config
for the intended peripheral. For example if it was the I2C peripheral, the GPIOPinTypeI2C()
would configure the pins with internal pull-ups for the sda and sca lines and connect
the external pins to the I2C peripheral.

Posted in Uncategorized | Leave a comment

Sleeping threads using events in python

So today i needed to find a way to sleep() a thread in python without blocking the other threads. For some reason, time.sleep() wasn’t cutting it and was blocking my main thread.

Well, unfortunately python dosen´t have a thread.sleep() (as far as i can tell) so we need to find a way around that.

Enter Timer and Event.

Event is a simple, thread-safe object that represents an (you guessed it) event. This object can be set() to signal that the event occurred and, more importantly, it can be waited by other threads until it’s set().

The Timer is a little more complicated. The Timer is a subclass of thread and is used when we want to execute and action after a set period of time. The Timer class takes at least two arguments, the time to wait (sleep… 😉 ) and the callback function that will be called after the time runs out. We can also pass a list of arguments that will be then passed to the callback function.

So now we have everything we need. An object that can be waited by some threads and set() by another and an object that will execute an action (inside another thread but that is not relevant for now) after a preset period of time.

The solution is now simple. In the thread you want to sleep, create the event, create the timer and pass the event as an argument to the callback function, start() the timer and wait() for the event to be set by the callback.

Let´s first create the event object:

event = Event()

Easy right? Now let’s create the function that will be called back when the timer is over:

def timeout_callback(event):
    event.set() # set's the event

Alright, now the timer with the event that needs to be passed to the callback and start it:

t = Timer(5.0, timeout_callback, [event])

Finally, let´s make our thread wait() for the event to be set:


Now our thread will block on the wait() call releasing the processor to the other threads so that they can go on about their business. When the timer reaches 0, the callback will be called, the event set, and our thread will return from the wait() call and continue doing it’s thing.

To put it all together (wraped in a convenient function):

from threading import Timer,Event

def timeout_callback(event):
    event.set() # set's the event

def wait_time(time):
	# Sleeps the thread for the given time (in seconds) whithout
	# blocking other threads
	event = Event()
	t = Timer(time, timeout_callback, [event])
	# Wait whithout blocking
	print('Event set!')

wait_time(5.0) # wait for 5 seconds


For this particular case, the event object must be unique to each thread, otherwise, if it’s shared by multiple threads, once one thread set’s the event, all other threads wainting on it will unblock and continue their work before their time runs out

Posted in Knowledge | Tagged , , | Leave a comment

The Go language

Unfortunately i haven´t had much time to mess around with my MP3 player recently, however I’ve started to learn a new programming language called Go and it is awesome!

The syntax is a little bit weird at first for someone who is used to write code in any traditional language like java, c or c#. For example, creating a function in c# that takes to int’s and returns another int  is done like this:

public static int Add(int a, int b){
    return a+b;

and in Go you do it like this:

func Add(a int, b int) int {
    return a+b

However, after a while it starts to make sense and it turns out that it makes reading the code so much easier! You can read it almost like plain english: “A function called Add that receives two integers, a and b, and returns an int”

Another aspect that i really love is the fact that you can run the command “go install ” from anywhere in the file system (there’s no need to be inside the project folder) and it will search for the packages in your workspace and build and install them automagically along with all the necessary libs, into the correct folders. Executable commands (your programs) go inside the “bin” dir and your library’s go inside the “pkg” folder, all neat and tidy. Another benefit of this is that, since the source code files all stay in the “src” folder, it´s trivial to add them to a repository like github.com whithout much fuss.

Well that is all for now. I’ll be posting some example code in my git repo as I go along learning Go in the next few days.


Posted in Knowledge, Uncategorized | Leave a comment

Project: MP3 Player – Design and goals

As promised here is the first post about my mp3 player project.

I´ll talk about mainly two things today: What are my goals  and what will be the basic design of the project.

Well for my goals, what I have in mind is actually quite a simple. I want to build an MP3 player with following components:

  • TFT LCD Screen with 320×240 resolution
  • Touch screen interface
  • SD Card for music/data storage

So there is nothing really special about it. All standard stuff.

As for my design, here is what i have in mind:

MP3 Player Diagram

(click for bigger image)

For the microcontroller, i will be using the Stellaris LM4f120H5QR. It is both a low-cost and powerful ARM microcontroller. It can operate at 80MHz and comes with all the standard peripherals like SPI, I2C, I2S, UART´s, lots of GPIO´s, etc. You can buy one from here: Stellaris Launchpad Evaluation Kit

For the LCD display I’m using a cheap chinese one from eBay like this one (or you could simply search for “3.2” TFT LCD Module Display + Touch Panel”). This displays are actually quite nice, they are cheap and even come with a touch screen and an SD Card socket! However they have a few problems. They are a little bit slow when filling the display completely and for some reason the one i got seems to be missing the SD Card controller IC (although I haven´t tested to see if it works without it). But these are more annoyances than real problems since there´s rarely a need to fill the complete display over and over, and I can order the SD Card controller IC from eBay for a few cents and solder it to the board in no time.

Another grip that I have with this display is that, although the LCD controller is capable of SPI communications, the people who built this display decided to disable that leaving only the parallel interface! So i had to improvise a little solution in order to spare a few more GPIO pins on the Stellaris (else i would need 22 GPIO pins just to control the LCD! :O)

As for the mp3 decoder chip, I will be using a VS1053 made by VLSI (link). It cost about 15€ (~20 US Dollar) and comes with a lot of stuff! Although it is an overkill for these project, you should see their flagship chip, the VS1005! That thing is just… uau!

Well that’s it for now. There are a few problems with this set up but I will talk about them in future posts. Because of that, please note that this design will most probably change!  It is my first time doing a project at this scale so I’m sure there will be quite a few changes that will need to me made.

Oh and I’ve finally decided to give my project a name: Varuna MP3 Player (or Varuna Player for short)! Just to make it official :p

To those curious, Varuna is the name of the God of the sky and water in the Hindu mythology. There is nothing special about “Varuna” per se. I just like the names of hindu deities and other mythological stuff!

See you soon!

Posted in Projects, Varuna MP3 Player | Leave a comment

First post!

Welcome to my little corner of the Internet!

I’ve decided to create this blog, not only as a way to help document my little (and BIG) projects and to try and show that computer´s aren´t all that magical machines (although occasionally they do release magic smoke! XD), but also to try and share a little of my knowledge in the hope that someone, someday will learn something useful out of all this! 😉

As a way to kick-start this blog, i´ll make, in the following months, a series a post´s related to my first big project: a portable MP3 player! I´ll try to talk about every single detail i can about the project going all the way from the beginning, like designing and making prototypes for the various modules, until the very end where (hopefully) i´ll have a fully working mp3 player!

Well, this is all for now. See you soon!


Posted in Uncategorized | Leave a comment