What should be the output to the following code ? I am confused because I am getting a slightly different output everytime . Any other advise would also be appreciated .

#include<iostream>
#include<SFML\System.hpp>



void apple_thread(void *data)
{
    using namespace std;
    for(int i = 5 ; i<11 ; i++)
    {
        cout<<"I have "<<i<<" apples . "<<endl;
    }

}

void main()
{
    sf::Thread thread(&apple_thread);
    thread.Launch();
    using namespace std;
    for(int i = 5 ; i<11 ; i++)
        cout<<"I have "<<i<<" oranges . "<<endl;
    getchar();

}

What output are you seeing?

I don't use SFML, so maybe there's someone better qualified to support you here (or on an SFML-related site). But it looks to me as though you have two threads running, the main thread and a second thread that you launch, and each writes out statements from within a loop. I'd expect to see some variation in the order of output statements being written out, depending on how the threads run.

The problem you see is that c++ stream library may or may not be thread safe meaning that you might see almost any random output or a mixture of the two. Read this thread for more information.

If you want specific output then you will have to add thread synchronization techniques, such as creating and using a mutex. Here are a few google links you might want to read.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.