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!