Skip navigation.

Ambassador

The Royal C++ Embassy

Concurrency, garbage collection and C++, a naive approach - 1

, ,

C++, as a mainstream, modern and a strong language, has evolved and is still evolving to deal with today's programming challenges. We have started using garbage collection enabled virtual run-time environments for a more than a decade in mainstream production, although (compacting) garbage collection has been implemented in 1970s. Similarly, parallel computing and concurrency discoveries have been made decades ago. C++ has been invented in early 80s and standardized in 1998. C++ has refused to have garbage collection, probably because people were treating C++ "a better C" or "C with classes" for a long time. C++ has refused threads, locks and similar concepts as well.

I will refer primarily to Herb's thoughts, because I happen to believe he explains both of these concerns very clearly.

Threads
The "thread" word appear exactly once in ISO/IEC 14882:2003 (Programming Languages - C++), in exception handling section. There are some reasons behind it, and they are primarily:
  • Threads are not portable across platforms.
  • Thread is a very low level term (so is pointer, right?)
  • C++ has been used in single-threaded applications, primarily (arguably)
  • Due to portability problems, OS vendors and third-party libraries already provide a C API, and one can build a C++ abstraction layer upon them, if required.


Each system has its own threading mechanism. Some systems may not even honor threads, and go without them. Never mind required hardware support. C++ is a mainstream language on embedded platforms as well. Actually, as far as I know, even .NET people can't do without touching some C++ code on embedded platforms. I know compilers that do not comply with standard, support exceptions, templates and things like those that we use for first-class application development, but they have to go without those due to platform's restrictions and complexity introduced to implement those features in compiler. Since thread is conceptually very low level, it's really hard to standardize it. Because this may require threading and synchronization API to be standard or at least equivalent across operating systems. I think, these were primary reasons why threads have not been mentioned in the standard - well, because thread itself is really hard to standardize.

Thread Synchronization
Theory is simple: one CPU (single core) can execute exactly one instruction at any given point in time. n CPUs can execute n instructions at any given point in time (no pipelining). Our purpose is sharing processing power to execute series of instructions that belong different tasks. Because different tasks, usually, require different things. For example, when performing a slow IO operating, CPU can switch to another task until IO operation completes.

The problem starts when we have some data that we need to share among threads. When we want to change this shared data, we need to guard it from being accessed by other tasks running "concurrently". Therefore, we need to synchronize (some peope say "serialize") access to this shared resource with a set of syncronization objects provided by either operating system or third-party library vendor. These are, today, primarily lock based solutions. They are widely used, as lock based applications are simpler to write. Even with lock based designs, we run into problems.

Lock-based synchronization
Example (Herb's very good example):

If we had a piece of code, say A, and we can prove that this code has implemented locks 100% correctly. If we also had a piece of code, say B, and we can prove that it is also 100% correct. We cannot say the result will be 100% correct, if we use them together; they simply are not composable.


Because code A may take a lock, call something in code B, it takes a lock and calls something in A, which is guarded with a lock and there we have a deadlock.

Locks are simpler to understand, but still hard to understand. In lock based synchronization, we usually make system calls, because it's operating system kernel that deals with locks. "Hey, critical sections are user space objects", I hear. Yes, but critical section's scope is restricted to threads of the same process, and as far as I know, there is no such concept in POSIX standard, so no UNIX variant implements it.

The logic behind the locks are simple (pseudo code):
while (!AcquireLock())
      WaitForRelease();

// .. rest of the code


A piece of code tries to acquire a lock. If it can acquire the lock, it continues execution. Otherwise, it waits (infinitely or arbitrary time or never waits and returns - depends on design and OS support). Code repeats these steps to continue its execution.

Problems with above (or similar, lock based) code:
  • Too many system calls
  • No prioritization
  • Contention
  • Potential deadlock (i.e. task cannot proceed, gets stuck)


People believe system calls, especially on today's modern, fast and cheap hardware, does not cause any performance degredation. I am against this theory. There should always be a performance concern in software - we cannot rely on fast and cheap hardware - this can't go like that and all this breeds is bad design and implementation.

Too many system calls introduce a performance problem. In priority scheduling, when locks are used, prioritization loses its meaning. Some systems perform priority inversion, which simply increases priority of thread that owns a lock. But it's still not the proper solution. If threads try to acquire an already held lock, lock contention begins. The longer the lock is held, the more likely there is another task trying to acquire it.

There are some certain and simple rules in lock based approach and one of them is "never call unknown code while holding a lock", never call virtual functions and others' code. As I mentioned above, quoted from Herb's talk, we cannot prove that two correct implementations of lock-based synchronization are still correct after we use them together. This may lead a deadlock, a lock that will never open because two or more tasks are waiting each other to release a lock that other holds (similarly, one single thread can deadlock itself, too).

In fact, it has never been too simple to write a correct lock based code. Computer scientists then developed some "lock-free" algorithms that do not employ locks. This is what Herb says;

...you need scientists to write correct lock based programs. But you need rocket scientists to write lock-free based programs... everytime you write a piece of lock-free code, you actually prepare a (academic) paper, and expect corrections...



Lock-free Synchronization
There are a couple of approaches to this subject, but I will primarily focus on transactions and simple CAS (compare and swap, or, compare and exchange).

The purpose is solving shared data problem by introducing atomic operations. Atomicity, by putting simply, means that an operation either completes or ends as if it's never begun. In transactional concurrency, which's an idea heavily used in database systems, too; system defines an invariant for end state and if at the end of an operation this invariant is not satisfied, transaction rolls-back (undoes its changes, if made any - never mind catastrophic scenerios) and restarts. Actually, I have got a set of pretty thick books discuss transactions and concurrency and it really is complicated, believe me. However, it's our job to challenge our very own complexities.

A lock free system does not become Alice's world, by just not to use locks, but tossing coins at the gates of "The Matrix" with Agent Smith - whether you should enter or not.

Lock based systems are like Newton mechanics - you can roughly estimate something. Lock free systems are like quantum physics - nothing is certain enough


as Herb says.

A lock-free system does not necessarily mean a wait-free system, although a wait-free system is lock-free by its definition. Transactional concurrency I will mention will try not to deal about catastrophic cases.

A transaction can be seen as an operation that either completes or returns to its initial state, as if it's never begun. There are several approaches to this issue, too. Basically, this is done by getting a snapshot (copy) of the data, modify its copy, check invariants and write it to its original location (commit). If another transaction tries to commit its own changes and sees its invariants, for example target object's value, are not satisfied, rolls back and restarts its operation.

Opera and opera

, , ,

Working at Opera doesn't necessarily mean that everybody loves opera. The former "Opera" is the "Opera Software ASA". The latter one is the theatrical presentation, as everyone on the planet - whether they use Opera Web Browser or not - knows.

I'm not really keen with opera, either. I have, however, had some warm feelings about it and asked my coworkers whether they like Opera, so that may be we can go and see a nice one someday. We have some "Den Norske Opera" ads in our room. So I happen to believe they do like it! We already have one opera building but it seems like Norwegians need a better and bigger one and a very nice opera building is being constructed in Oslo. Nonetheless, survey results was saying (some) Opera employees are not really into opera.

Out of 15 people (out of 280 people :smile: )I have asked, only 2 guys were neutral (neither hates, nor likes). The rest explicitly said "no, I don't like".

What does "opera" mean?
As I'm a super duper Latin linguistic, I can anaswer this question rapidly and clear enough for an average person to understand p:

Opera means "result of a work", derives from "opus", which means "creative work", usually used for music compositions.

Except "musical composition" part, that's what we do here; we do design and implement innovational software that affects the way people browse the web, making your web surfing experience more comfortable, secure, reliable and fast. We do it in accord, we are a big team and everybody does what they have to, on time and correctly.

An Opera employee does go to opera everyday, and he/she himself/herself does play in opera everyday, as being part of Opera web browser team, everyday. We invent stuff, we prepare trends, others follow it.

"Resistance is futile, you'll be assimilated!"

Follow the trends - Countries visited :)

, , ,

Everybody has got "Countries I have visisted" pictures. I have decided to get mine, too! Going one or two cities does not make someone visited whole country, but that's how system works.



create your own visited countries map
or vertaling Duits Nederlands

The tiny red spot on far east is Korea. I have been to Seoul - gorgeous city, like Istanbul, it's just big. I mean, it's big, bigger than London, Paris or any other big city in Europe. Istanbul's population, as far as I know, is greater than Seoul's.

I have never been to northern Norway (red region on top of the map), didn't see whole Italy, Spain and Netherlands (yet). I have spent long time in London and we (I and a friend) have actually planned to go to Manchester and Cambridge, but we loved London so much so we've stayed there.

Well, I haven't seen whole Turkey either! Furthest east point I have been to was Ankara, the capital, which is at the middle of the country. Furthest south point was Izmir, which is on Aegean sea, quite close to Greece. I have born and grown up at north west of Turkey. Here I am at north west Europe, Norway :smile:

So, basically, I have seen following cities:
Belgium:
Antwerp
Brusssels

France:
Paris (twice)

Italy:
Milano
Rome (partially, needs proper visit)

Netherlands:
Amsterdam

Sweden:
Goteborg
Malmo
Linkoping (in very near future)
Stockholm (in very near future)

Norway:
Oslo (of course)
Bergen

UK:
London

South Korea, Republic of:
Seoul
The city south east of Seoul (forgot its name)

Denmark:
Copenhagen (with car, from Oslo, great trip, thanks Arjan!)

Spain:
Barcelona
Malaga (soon)

Turkey:
Istanbul (of course)
Tekirdag (of course)
Edirne
Izmir
Ankara
Sakarya
Canakkale
Bursa
couple of more, I guess :smile:

Addition
What about "my virtual flights"?


This is where I have flown so far (in real world and in simulation :smile: ) I prefer Lufthansa, sometimes KLM.

Hoping that they don't speak the way they write

, , ,

Many many years ago, British has, well, reached India. British took something from Indians, Indians did take from British. English have left, but they have forgotten English in there, which today bleeds, suffers. As far as I know, nearly all India and Pakistan can speak English, as they are former British colony.

I am quite frustrated about the way they use English, however. I think the major reason behind blogging is frustration, and here is mine; bad English make any piece of text horrible.

Some words I have collected:
plz, u, ur (sometimes for "you are" as well), no1, every1, y, cuz, b4, l8r (well, I was using this as a "nick name" on IRC :D and it was changing to "c_u_l8r" when I was away), wat (just one letter for God's sake!), waz (for both "what's" and "was")...

What does it have to do with Indians and Pakistanis?
Believe it or not; one of my best friends is Indian, sitting next to me. He's a really good person, speaks and writes very good English. I have one more Pakistani friend and lots of Pakistani friends especially in London. Well, almost all pieces of text contain sentences formed with above words are authored by either an Indian or a Pakistani.

Also, I recall Microsoft Support Center clip - hilarious! So some of them really do speak terrible English, as you can see from the video.

"Ben cı, ci, çu, çü değilim!"

, ,

This is a Turkish text.
Discusses Ataturkism in Turkey, which I happen to believe major and most obvious dividing mentality but could not be discussed / accussed since it contains the "holy" (!) word Ataturk. When you google it, you may see some Islamic links as well. I, however, did not intend to relate the subject to Islam. My concern is completely different; basically, the freedom of speech and thinking. Nonetheless, those guys somehow divide citizens into two; those who are Ataturkist and those who aren't. Much like black and white in USA.

Bazi meslekler, isler vardir ya, mesela; pazarci, bakkalci (!), tamirci, vs. Bu Ataturkculuk konusu da aynen boyledir; "Ataturkcu" insanlar vardir. "Kilosu kaca?" diye sorasim gelir bazen, fakat gulmekten soruyu soramam. Bir de "dinci" vardir, o da din satar, mesela. Gerici, irticaci da vardir. Onlar pek muhtemelen "geri" ve "irtica" satmiyorlardir ama... o da onlarin meslegidir, saygi duymak gerekir. Simdilik ne sattiklarini biz bilmiyoruz, fakat bir kesim biliyor ki insanlari "gerici" yada "irticaci" diye ayirt edebiliyorlar.

Ben elektronik muhendisligi okudum, ozaman "elektronikci" derlerdi. Sonra yazilim uzerine calistim, artik "bilgisayarci" deniyor. "secmece bunlar! 1200 Amerikan dolari, abi"... gibi, sanki bilgisayar satiyoruz pazarda! Degilim diye haykiriyorum, kimse dinlemiyor. Neyse ki elektronik satmadim, yada "topcu" olup top satmadim, Allah'a sukur.

Bana kalirsa, boluculugun daniskasi "Ataturkculuk"tur. Yani bu zihniyet der ki; "iki grup insan vardir; Ataturkcu olanlar ve olmayanlar". Birsekilde Turkiye, icerisinde Ataturk gecen her cumleyi kutsal sayiyor ve bu boluculuge goz yumuyor. Nedendir bilinmez, Turkiye gercekten ozgurluge ve hurriyete alisamamis. Farkindalar mi bilmiyorum; bu durum sadece diktatoral rejimlerde olur ve bu durum bircok vatandasi Ataturk'ten uzaklastiriyor. Yani karalanan yine Ataturk oluyor. Batili dostlarim da dogulu dostlarim da Ataturk'un ne oldugunu kavrayamamislar. Kimisine gore diktator, kimisine gore kral, kimisine gore "bir grup soylem"... ben aciklayamayacagim icin, en iyisi hic dokunmayayim; "google it!" diyorum.

Neyse, herkes kendini ve yerini biliyorsa, zaten isimlerle ayirmaya luzum yoktur. Fakat ben bir konuya aciklik getirmek istiyorum; ben cı, ci, çu, çü degilim!

Politik dusuncemi merak ederseniz; ben liberal bir dusunceye sahibim, Turkiye'nin en bati noktasinda, batili bir ailenin cocugu olarak dunyaya geldim ve buyudum.

Realism addiction/fetishism (!) in flight simulation

,

One short part of the problem; people think time compression is bad but I think otherwise.

As a flight simulation addict, I want and expect higher realism. Because flying is fun only in real life, and definetely far less fun in virtual life. We buy add-ons, we enhance them, write our own. We become members of "virtual airlines" that are trying to fly, in virtual world, the same schedules and the same aircrafts with the real life. For example, Lufthansa has a flight from Munich to Istanbul, with flight number LH 3350, departs from Munich at 11:40 and lands to Istanbul around 15:10. (All times are local) There are various aircrafts for this flight, but most probably it'll be an Airbus A32x (at least, it was in my past 6 flights - in real world). To fly this in virtual world, you need to leave the gate at 11:40 with an A32x (A320 or A321, may be). Boeing 737 can fly the same route, too. But you cannot do it, because the real Lufthansa, as far as I know, does not operate B737 for this flight (they may operate B727, though).

The problem is not with being forced to choose the same aircraft and schedule, but it's with the time anti-compressionism. Up to some extent, I find it logical in online flying. If you are flying over a manned airspace and everybody flies with high time compression, hey what can controllers do then? So this can be important in manned airspaces where traffic is (rather) dense. Lufthansa Virtual Airline does not force pilots to fly online or without time compression; "just fly", they say.

Turkish Virtual Airline, however, requires online flying and they do not allow time compression. Well, actually it's probably because (virtual?) pilots are flying online and need to communicate with (virtual?) controllers controlling various (virtual?) manned airspaces, so they better do not (virtually?) fly with time compression.

The basic answer of time-compression-haters is that; "because you just can't do it in real life?". I nod... and think... Ok, it's time to look around yourself "in real world". I mean, when you are virtually flying, stop the game and take a look around yourself. In real world, all we have are simply; a PC, a force feedback joystick or a yoke (with some pedals, and throttles, may be), a headphone (or a set of surround speakers, which does not work like a surround, anyway), a keyboard, a mouse, at least one screen and the nice chair that we sit (mine is a cheap bad kitchen chair, believe me, and I cannot sit longer than 3 hours). Does it look like a real A320? Do we really talk with ground staff, with a "real" co-pilot, smell fuel or any hostesses bringing coffee? Sorry to disappoint you, but none happens, dude! How many of virtual pilots use up-to-date charts or even FMC (look, this is important; I bet majority of those multi-engine-jet pilots that fly IFR flights do not use an aircraft equipped with FMC)? I bet more than 80% of virtual pilots has never taken a look at check-lists! We still don't have proper 3-D equipment - it's a (set of) monitor(s) (and the more you duplicate monitors, the more it gets worse). We still don't have proper surround sound (thanks to my washing machine sometimes making real engine sound effects). Finally, what we use (well, most of us) is a PC - not even a simulator that moves or shakes.

We sometimes have long haul flights, say, taking 7-10 hours. Unfortunately, strictly speaking, one needs to "waste his/her time" (literally) and fly without time compression. I cannot do it, I know exactly one person who did it exactly twice and that's it. I am doing this for fun and I'm not a masochist nor have that much time to waste. I believe sadist-masochist balance in those virtual airlines that does not allow time compression is ok, so I just leave them.

Safe and nice landings, and don't you forget to fly "with" time compression :wink:

Armavia Flight 967 - Pilot error

, , ,

Russians figured out how Armavia Flight 967 crashed - the Airbus A320 crashed at Sochi, Russia, killed 113, at May 3, 2006; it was a pilot error. I'm not a commercial pilot (yet, at least :D ), not an authority on instrument approaches - just my thoughts.

Disengaging autopilot
I happen to believe - may be I am wrong - depending on how bad weather is and state of aircraft, disengaging AP and stabilize aircraft, adjust pitch and throttle manually could work better. A320 is one of the most sophisticated (first fly-by-wire) aircrafts that employ 7 flight computers that react far faster than a human and those computers protect aircraft from human errors as well.

According to Russian NTSB, Flight 967's pilot (Captain Grigory Grigoryan) has disengaged AP at 1100ft AGL (above ground level) while making second of four 90 degrees turn, executing a go-around.

The advantage of AP is that it's got multiple computers continuously calculating whole aerodynamics, complex physics. I think disengaging AP at that low altitude under bad weather conditions was not the best idea.

Winds
The major problem with wind is change in its direction rather than its strength. If it wind's direction changes frequently, a human may not respond fast enough. AP can do better than a human under such circumstances, I think. Never mind all those pilots take a test every 6 months on simulator against crazy winds and windshear.

I remember worst turbulence of my life, it was an A321. I think pilot disengaged AP, because it was AP that did some immediate pitch up-down and increase-decrease thrust - it was scary. We had smoother turbulence after a little shaking. I think that little shaking happened after AP disengaged, thrust was also stabilized. Of course, we were cruising at 36000ft, probably around .78 mach speed; in other words, pilot(s) had lots of things to do and time, if something would have gone wrong.

I sometimes think aircrafts became far too complex to understand. Pilots have difficulties to choose the right action to take against real-tough problems, they lose their way in riddling checklists (filled with "if"s). Complexity is introduced to achieve higher safety. Some pilots do not trust computers, they compete with computers (not implying Captain Grigory Grigoryan did this). The worst action to take in a fly-by-wire aircraft, I think, is to distrusting/competing with computers and risking everything.

Peace on Armavia Flight 967.

Anti-Americanism

, , ,

Politics is not my job, but I spotted an important news on Reuters.

I could not, however, see any research in this news that asks or answers "why" question. They asked South Koreans, at least, and number of North Korea supporters increased while US supporters decreased. Few years ago, it's decreased in Turkey as well. This all happened after US invaded Afghanistan and Iraq. Turkish do not believe there is an Al-Queda - it's all America's toy to invade somewhere. According to a former secret service authority, "Al-Queda can be defined as 'Made in Middle East. Copyright (c) United States of America.".

Countries having nuclear warheads are dangerous - no doubt, it's bad for everyone, including themselves. However, US is far more dangerous to the world without those countries. Think again; US did all sorts of vile and disgusting things in Iraq, in Afghanistan and they named it "bringing democracy" or "war on terror". Now, I wonder (a lot) why they do not want to bring the very same democracy to North Korea or to Iran... Iran never threatened any EU member (as far as I remember), but they just threatened Israel - and I happen to believe that they are right in these days.

US is preparing to sell (or even already sold) weapons (precision guided missiles, I guess, which is the one just hit UN post) to Israel. It's obvious there is a commercial concern behind all this veto to peace/cease fire in middle east. Never mind Rice's "New Middle East" plans. By the way, wasn't middle east already made by British? (I mean, the borders, countries, etc are all hand-made by British, right?)

I was shocked after hearing Israel has killed 4 UN personnel. But it is a good chance for world to revise their actions/thoughts against Israel. I think jews don't understand the fact that if they continue taking such animalistic actions against civilians (repeat, "civilians"), the world will hate them, world will forget about Hezbollah's rockets.

Wrong approach to smokers

, ,

Everybody knows "smoking is bad". Chemical structure of tar and other chemical substances in the smoke can cause cancer, particularly, lung cancer.

Smoking harms... blah blah blah...
I keep seeing people telling "how bad smoking is". But this is, in my personal opinion, something utterly wrong - you cannot convince a dependant with a bag of words. Instead of blaming cigarette, health organizations/doctors/etc. should try to minimize the damage and help smoker during critical period of giving up cigarette. To give up smoking, dependant needs at least 3 months. What I say is, give nicotine in another form, decrease every day, and make that period, say, 6 months. With no or less pain throughout 6 months fed with weakened nicotine, I bet people will not require smoking. If...

If smoking habit is a result of nicotine dependency, which is questionable, I think, then smokers can give up smoking with little help. If, however, smoking is not just about nicotine, then we need a workaround. Smoking could feel nice, but it also feels painful and smells bad (even smokers hate it). Never mind how cigarette stains teeth, which also disturbs smokers (don't you forget how much dental surgery costs). But as I said, people do smoke because they enjoy. There are just a couple of questions:
  • What exactly do they enjoy?
  • Is there an alternative and smoother way to give up smoking, instead of giving up immediately?
  • Instead of showing smokers disgusting lung, vein and heart photos, teaching them anatomy (If I smoke, my sigmoid colon gets darker and my ulnar nerve squeezes. Never mind my spinal cord breaks...) can we find a proper way to guide them to give it up?
  • Did we make those health organizations and campaigns free?
  • How can we stop next generations becoming a dependant?


I think those anatomy classes, cadaver lungs, etc. is nothing but too far from helping smokers.

"If you smoke, you die"
You gotta be kidding! I remember answer from one of my elder friends;
"My grandfather died 80 years old, in natural way, he was smoking slightly more than 1 pack everyday. Most of his non-smoker friends have died years ago from various reasons, like car crash, drawning, heart disease and cancer."

Everybody's gonna die! This lie just does not work!

Imagining forensics on piece of software
I was thinking how stupid it could be to place screenshots/photos of a crashed application or a memory dump to a secretary in the office and tell her not to visit stupid web sites that potentially has spyware which causes this sort of desease... Well, it's nothing that causes dependency, but on the other hand, my approach could be pointless... "Ok, we know, badware is bad". It's obviously disturbing to see a crashed computer (in particular, Windows, or even more particularly, Internet Explorer :D ). "If you keep visiting those sites, your computer will crash like this (bang!)".

Just discovered Flightgear

, ,

I have just discovered Flightgear - the free flight simulation running on FreeBSD!

It seems like there are lots of aircrafts (right now, downloading) ready to fly. I am trying to get my joystick working. So far, I have installed linux-js (/usr/ports/devel/linux-js) and got /dev/input/js0 up. However, it seems like the game expects (something like) /dev/joy0.

ATC and AI sound like coller than Microsoft Flight Simulator 2004. I have not tested completely, but I just listened AI chatter and it sounds good :smile: so are ATC instructions, for example it says "good day", like in real world.
Download Opera, the fastest and most secure browser
December 2009
S M T W T F S
November 2009January 2010
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31