mardi 15 août 2017

Why does my thread not run in background?

in the list bellow, I expect that as I call t.detach() right after the line when the thread is created, the thread t will run in background while the printf("quit the main function now \n") will called and then the main will exit.

#include "stdafx.h"
#include <thread>
#include <iostream>

void hello3(int* i)
{

    for (int j = 0; j < 100; j++)
    {
        *i = *i + 1;
        printf("From new thread %d \n", *i);
        fflush(stdout);

    }

    char c = getchar();
 }

int _tmain(int argc, _TCHAR* argv[])
{
    int i;
    i = 0;
    std::thread t(hello3, &i);
    t.detach();
    printf("quit the main function now \n");
    fflush(stdout);
    return 0;
}

However from what it prints out on the screen it is not the case. It prints From new thread 1 From new thread 2 .... From new thread 99 quit the main function now.

It looks like the main function waits until the thread finishes before it executes the command printf("quit the main function now \n"); and exits.

Can you please explain why it is? What I am missing here?

Thank you

Aucun commentaire:

Enregistrer un commentaire