簡體   English   中英

Boost::thread 如何獲取指向調用我的 function 的線程的指針?

[英]Boost::thread how to get a pointer to the thread where my function is called?

使用boost::thread我如何從 function 中獲取指向當前正在執行我的 function 的boost::thread的指針?

以下內容不適合我:

boost::thread *currentThread = boost::this_thread;

您可以使用 boost::this_thread 來引用您使用它的同一線程。

http://www.boost.org/doc/libs/1_41_0/doc/html/thread/thread_management.html

您必須小心,因為boost::thread是可移動類型。 考慮以下:

boost::thread
make_thread()
{
    boost::thread thread([](boost::thread* p)
    {
        // here p points to the thread object we started from
    }, &thread);
    return thread;
}

// ...
boost::thread t = make_thread();
// if the thread is running by this point, p points to an non-existent object

boost::thread object 在概念上與線程相關聯,但不是規范地與其相關聯,即在線程過程中,可能有多個線程對象與它相關聯(在給定時間不超過一個)。 這就是boost::thread::id在這里的部分原因。 那么你想要達到的究竟是什么?

如果您瀏覽 Boost Thread 文檔的全部內容( http://www.boost.org/doc/libs/release/doc/html/thread.htmlZ80791B3AE7002CB88C24/6876DFA/Adoc8C24 /6876DFA/doc88C24/6876DFA/ 1_60_0/doc/html/thread.html如果第一個鏈接斷開),您會發現沒有提供 function 來獲取指向boost::thread ZA8CFDE6331BD59EB2AC96F8911 的指針。

但是,您可以自己解決此問題; 一種解決方案是使用 map,將boost::thread:id映射到boost:thread* ,然后從您的線程中訪問該 map 以獲取指針。

例如:

#include <cstdio>
#include <map>

#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>

std::map<boost::thread::id, boost::thread*> threadsMap;
boost::mutex threadsMapMutex;  // to synchronize access to the map

boost::mutex stdoutMutex;  // to synchronize access to stdout

void thread_function()
{
    threadsMapMutex.lock();

    // get a pointer to this thread
    boost::thread::id id = boost::this_thread::get_id();
    boost::thread* thisThread = threadsMap.find(id)->second;

    threadsMapMutex.unlock();

    // do whatever it is that you need to do with the pointer

    if(thisThread != NULL)
    {
        stdoutMutex.lock();
        printf("I have a pointer to my own thread!\n");
        stdoutMutex.unlock();
    }
}

int main()
{
    threadsMapMutex.lock();

    // create the threads
    boost::thread thread1(&thread_function);
    boost::thread thread2(&thread_function);

    // insert the threads into the map
    threadsMap.insert(std::pair<boost::thread::id, boost::thread*>(thread1.get_id(), &thread1));
    threadsMap.insert(std::pair<boost::thread::id, boost::thread*>(thread2.get_id(), &thread2));

    threadsMapMutex.unlock();

    // join the threads
    thread1.join();
    thread2.join();

    return 0;
}

PS 我剛剛注意到你在寫完這篇文章后發表了評論,說你實際上正在使用這個解決方案。 哦,好吧-我仍然發現正式發布您的問題的答案以及潛在解決方案的(工作)示例代碼是有用且完整的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM