gpt4 book ai didi

c++ - 从线程中获取 native 句柄?

转载 作者:可可西里 更新时间:2023-11-01 09:48:09 25 4
gpt4 key购买 nike

我正在使用 VS2012,我想在运行的线程中设置线程优先级。目标是用最高优先级状态初始化所有线程。为此,我想为线程获取一个HANDLE

我在访问对应于 thread 对象的指针时遇到一些问题。

这可能吗?

从调用主线程,指针是有效的,从 C++11 线程它被设置为 CCCCCCCC。可以预见的是,取消引用一些无意义的内存位置会导致崩溃。

下面的代码是显示问题的简化版本。

#include "stdafx.h"
#include <Windows.h>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>
#include <atomic>
using namespace std;
class threadContainer
{
thread* mT;
condition_variable* con;
void lockMe()
{
mutex m;
unique_lock<std::mutex> lock(m);
con->wait(lock);//waits for host thread
cout << mT << endl;//CCCCCCCC
auto h = mT->native_handle();//causes a crash
con->wait(lock);//locks forever
}
public:
void run()
{
con = new condition_variable();
mT = new thread(&threadContainer::lockMe,*this);
cout << mT << endl; //00326420
con->notify_one();// Without this line everything locks as expected
mT->join();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
threadContainer mContainer;
mContainer.run();
return 0;
}

最佳答案

#include <mutex>
#include <condition_variable>
#include <iostream>
#include <atomic>
#include <thread>

class threadContainer {
std::thread* mT;
std::mutex m;
void lockMe() {
// wait for mT to be assigned:
{
std::unique_lock<std::mutex> lock(m);
}
std::cout << "lockMe():" << mT << "\n";
auto h = mT->native_handle();//causes a crash
std::cout << "Done lockMe!\n";
}
public:
void run() {
// release lock only after mT assigned:
{
std::unique_lock<std::mutex> lock(m);
mT = new std::thread( [&](){ this->lockMe(); } );
}
std::cout << "run():" << mT << "\n"; //00326420
mT->join();
}
};

int main() {
threadContainer mContainer;
mContainer.run();
return 0;
}

试试吧。

关于c++ - 从线程中获取 native 句柄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14450643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com