Weird thread output

Look at this code and it's output:
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
#include <iostream>
#include <boost/thread.hpp>
 
using namespace std;
using namespace boost;
 
void thread1()
{
        cout<<"Hello World for the first time\nin the first(1.) thread!"<<endl;
		this_thread::sleep(posix_time::milliseconds(1));
		cout<<"Hello World for the second time\nin the first(1.) thread!"<<endl;
}
 
void thread2()
{
        cout<<"Hello World for the first time\nin the second(1.) thread!"<<endl;
		this_thread::sleep(posix_time::milliseconds(1));
		cout<<"Hello World for the second time\nin the second(1.) thread!"<<endl;
}
 
int main()
{
    thread a(thread1), b(thread2);
    cout<<cout<<"Hello World for the first time\nn the main() thread!"<<endl;
	this_thread::sleep(posix_time::milliseconds(1));
	cout<<cout<<"Hello World for the second time\nin the main() thread!"<<endl;
	a.join();
	b.join();
}
0x47bfc4Hello World for the first time
n the main() thread!
0x47bfc4Hello World for the second time
in the main() thread!
Hello World for the first time
in the first(1.) thread!
Hello World for the second time
in the first(1.) thread!
Hello World for the first time
in the second(1.) thread!
Hello World for the second time
in the second(1.) thread!
Last edited on
Sorry,
Last edited on
I change it to show what was actually the problem
Isn't it weird?
Why is the first thread executed twice, and the second isn't?
Last edited on
closed account (o1vk4iN6)
Can't tell if spam.
It's not! It's the real output from my program!
Last edited on
closed account (o1vk4iN6)
 
const int n = 22500000; // many copies 
Why so many copies?

n/2 == 22500000/2 == 11250000
You use a loop and print the same message 11250000 times.
^^ Agree with Xerzi and Viliml! Your parameters (boolean statement) says to stop at a crazy high number so it's going to print that until you hit those values in the boolean statement.
Sorry, It wasn't about so many times, but more repetitions of threads after they are finished!
So I changed the thread to something simpler
closed account (o1vk4iN6)
So you have 3 threads, each outputting 4 lines, and there's a total of 12 lines outputted. So what's the extra ?
Last edited on
I dont know what the original code was, but the current code and output look fine to me although I dont think the order is guaranteed. What output did you expect?
Oh,i just forgot to make the second thread output the number 2. Instead of 1. Sorry!
Topic archived. No new replies allowed.