Puzzle – Easy : C++ Multithreading

Below is a small and easy puzzle on multi-threading, ideal for beginners. And to be honest, title should have been “C Multithreading” since it uses pthreads, and not C++11 for threading.

#include <pthread.h>
#include <unistd.h>
#include <iostream>

using namespace std;

int i;

void* f1(void*)
{
    for (i = 0; i < 10; i+=2){
        cout << i << endl;
        sleep(1);
    }
    return 0;
}

void* f2(void*)
{
    for (i = 1; i < 10; i+=2){
        cout << i << endl;
        sleep(1);
    }
    return 0;
}

int main()
{
    pthread_t t1, t2;
    pthread_create(&t1, 0, f1, 0);
    pthread_create(&t2, 0, f2, 0);
    pthread_join(t1, 0);
    pthread_join(t2, 0);
}

So what would be the output? In what order numbers will be printed? That’s the small puzzle for you.

To make you really think, I won’t give answer. You are free to share your answer in comments though. And hey running the program without thinking would be considered cheating!

Don’t you cheat!

Advertisements
This entry was posted in Programming and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s