Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

multithreading - Delayed start of a thread in C++ 11

I'm getting into C++11 threads and have run into a problem.

I want to declare a thread variable as global and start it later.

However all the examples I've seen seem to start the thread immediately for example

thread t(doSomething);

What I want is

thread t;

and start the thread later.

What I've tried is

if(!isThreadRunning)
{
    thread t(readTable);
}

but now t is block scope. So I want to declare t and then start the thread later so that t is accessible to other functions.

Thanks for any help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

std::thread's default constructor instantiates a std::thread without starting or representing any actual thread.

std::thread t;

The assignment operator moves the state of a thread object, and sets the assigned-from thread object to its default-initialized state:

t = std::thread(/* new thread code goes here */);

This first constructs a temporary thread object representing a new thread, transfers the new thread representation into the existing thread object that has a default state, and sets the temporary thread object's state to the default state that does not represent any running thread. Then the temporary thread object is destroyed, doing nothing.

Here's an example:

#include <iostream>
#include <thread>

void thread_func(const int i) {
    std::cout << "hello from thread: " << i << std::endl;
}

int main() {
    std::thread t;
    std::cout << "t exists" << std::endl;

    t = std::thread{ thread_func, 7 };
    t.join();

    std::cout << "done!" << std::endl;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...