|
-
December 30th, 2010, 06:39 PM
#1
C++ with Boost Thread Library, execution is not random?
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.
-
December 30th, 2010, 06:49 PM
#2
Re: C++ with Boost Thread Library, execution is not random?
Probably because of time-slices. All treads are executing for a slice of time before another thread gets to execute.
-
December 30th, 2010, 08:42 PM
#3
Re: C++ with Boost Thread Library, execution is not random?
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?
-
January 1st, 2011, 08:54 AM
#4
Re: C++ with Boost Thread Library, execution is not random?
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|