简体   繁体   中英

c++ running code on secondary std thread

I searched over 2 hours in google but I couldn't find an answer to my question:

I'm using c++ on windows 8 (x86) (visual studio express 2012)

I want to run a method from my worker std::thread on the process's main thread. I tried to create a reference of the two threads using their std::thread::id and then swap them, but I was not able to create the references.

Following method is called from my secondary thread:

[..]

void run(bool *running, thread::id _mainThreadId)
{
   while(*running)
   {  
        thread mainThread(_mainThreadId);
        thread thisThread(this_thread::get_id());
        thisThread.swap(mainThread);
        //mainThreads work:
        [..]
        thisThread.swap(mainThread);
        //thisThread again
   }
}

But when I try to compile my project there appeares an error that shows the constructor thread(thread::id) doesn't exist.

My question:

Is there a better way to run code on another thread? And is there a way to get a reference to a thread using it's id?

Thanks in advance!

PS: Sorry if there are grammatically mistakes. I'm from Germany. :)

Each thread is like a program running sequentially, you can't just make it jump to some other part of the program arbitrarily.

What you're asking for would be equivalent to starting yet another thread, perhaps pausing the original one until it completes, and getting this new thread to do what you want. This is because each thread has an instruction pointer that tells it where it is. Each thread also has registers and a stack, etc. If you want to make a thread do something different you would have to save all this state, do your business and then restore all the state. This is equivalent to just creating a new thread (where the operating system will save all the state for you).

It might be worth asking why you want to run a method in another thread. The only way to sort of do what you're asking is to send the other thread a message saying "please run this method with these arguments and give me the result", but this is generally pointless. If you need some sort of permissions that the other thread has, it should be possible to ask the operating system to grant your thread those permissions.

I don't actually get that swapping you are doing. If your intention was to deffer the execution to different thread it is not how it's done:

You need to pass a pointer to a function while thread creation. This function will be executed in separated thread. If you want to wait for it you join to the thread. Have you checked the example in thread documentation?

If you want to run something on another thread, you'll need to communicate some information to that other thread to inform the other thread about that. You cannot "swap" threads an hope that something is running on another thread!

One approach is to have message queues for your threads where you'd send jobs and each thread is just looking at its message queue and processes whatever is coming from that queue, eg:

int main() {
    SomeThreadEnabledQueue<std::function<bool()>> mainQueue;
    // kick of other threads possibly passing a pointer to the queue, etc.

    for (bool done(false); !done; ) {
        std::function<bool()> job = mainQueue.pop();
        done = job();
    }

    // join other threads, etc.
 }

You other thread would then send a suitable message to your thread by adding a suitable message to mainQueue() :

void run(std::atomic<bool> *running,
         SomeThreadEnabledQueue<std::function<bool()>>* queue) {
   while(*running)
   {
       // do whatever
       queue->push([=](){ /* what the other thread should do... */; return false; });
       // if necessary for the work to be completed, transfer a future and wait on it
   }
}

The above approach certainly works to get specific work items executed on a specific thread. Whether having to execute something on a specific thread is a good idea is a different question, though. Typically it works better to have a thread pool and making sure that certain objects are only run by at most one thread at a time.

Note that I changed the running argument which seems to be a pointer to a bool which is changed in another thread to be std::atomic<bool> : reading a value being changed in another thread without synchronization creates a data race and, hence, undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM