Click to See Complete Forum and Search --> : C++ with Boost Thread Library, execution is not random?


The_Journey
December 30th, 2010, 05:39 PM
Hi, so I created a test program as such:

#include <boost/thread.hpp>
#include <iostream>

class Thread1
{
public:

void operator() ()
{
for (int i = 0; i < 100; ++i)
{
std::cout << "From Thread1: " << i << std::endl;
}
}
};

class Thread2
{
public:

void operator() ()
{
for (int i = 0; i < 100; ++i)
{
std::cout << "From Thread2: " << i << std::endl;
}
}
};

int main(int argc, char* argv[])
{
Thread1 hr1;
Thread1 hr2;
boost::thread* thr1 = new boost::thread(hr1);
boost::thread* thr2 = new boost::thread(hr2);
boost::thread_group thr_group;
thr_group.add_thread(thr1);
thr_group.add_thread(thr2);
thr_group.join_all();
}

The output I got was:
From Thread2: 0
From Thread2: ...
From Thread2: 99
From Thread1: 0
From Thread1: ...
From Thread1: 99

Can anyone explain to me why the output isn't random? From what I know, the output should be a mix between Thread1 and Thread2, but it isn't.

Am I doing something wrong?

Thank you.

S_M_A
December 30th, 2010, 05:49 PM
Probably because of time-slices. All treads are executing for a slice of time before another thread gets to execute.

The_Journey
December 30th, 2010, 07:42 PM
Can you explain that again? I'm not sure I'm understanding you too well.

How can I get it to the execution to be more random?

S_M_A
January 1st, 2011, 07:54 AM
Every (proper) OS lets all tasks run for a short period of time. When and how long depends on the individual tasks priority and the time slice. See here for instance http://en.wikipedia.org/wiki/Preemption_(computing)

The only thing you can do to make them run a bit randomly is to make the tasks yield its current time slice and by that handing over the execution to other task (or anything that needs to be run in the system). However, trying to make anything that behaves the same way from execution to execution will be impossible due to a lot of issues so it's better to just accept that (in this context) you can't predict when or in which order the tasks will be executed.