Member Avatar for thendrluca

hi all! :)
well i wrote a sample code to test threads
and i don't get what i want
the problem is that the thread i created is starting directly after i create it?
but he must start when my j is equal to 25 and then i joining the thread
what is the problem?
screen: Result
code:

#include <iostream>
#include <thread>
#include <Windows.h>
using namespace std;

void f1()
{
    for (int i = 0; i < 50; i++) {
        cout << i << endl;
        Sleep(100);
    }
}

void f2()
{
    cout << "Hello World1" << endl;
}

int main()
{
    thread t1(f1);

    for (int j = 0; j < 50; j++) {
        if (j == 25)
            t1.join();
        cout << j << endl;
        Sleep(500);
    }


    cin.get();
}

thanks in advance :)

You should create the thread object when you want it to start. And the join() function is basically to wait for the thread to finish (i.e., join the thread with the current thread). If you want the thread to start when j is equal to 25 and then finish it at the end, you can do this:

int main()
{
    thread t1;   // default-construction means "no thread".

    for (int j = 0; j < 50; j++) {
        if (j == 25)
            t1 = thread(f1);   // create (start) and move a thread into 't1'.
        cout << j << endl;
        Sleep(500);
    }

    t1.join();

    cin.get();
}
commented: this is what i searching for :) thx +0
Member Avatar for thendrluca

thx a lot :)
this is what i searching for :)

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.