我正在研究广泛使用多线程的模拟。问题是,直到现在我从未使用过任何互斥对象来保护我的数据。结果,我遇到了一堆段错误。
我正在尝试使用互斥锁锁定/解锁 while : reading/writing 但这会导致我出现另一个段错误:
#0 77D27DD2 ntdll!RtlEnumerateGenericTableLikeADirectory() (C:\Windows\system32\ntdll.dll:??)
#1 00000000 ??() (??:??)
当然,我创建了一个测试项目,我在其中针对基本情况应用了锁定/解锁功能并且它有效,这是一个基本示例,展示了如何使用 GLFW 处理 Mutex 对象:
#include <GL/glfw.h>
#include <iostream>
#include <vector>
using namespace std;
vector<int> table;
GLFWmutex th_mutex;
void GLFWCALL Thread_1(void* arg) {
glfwLockMutex(th_mutex);
table.pop_back();
glfwUnlockMutex(th_mutex);
}
void GLFWCALL Thread_2(void* arg) {
glfwLockMutex(th_mutex);
table.erase(table.begin());
glfwUnlockMutex(th_mutex);
}
int main()
{
bool running = true;
GLFWthread th_1, th_2;
glfwInit();
if( !glfwOpenWindow( 512, 512, 0, 0, 0, 0, 0, 0, GLFW_WINDOW ) )
{
glfwTerminate();
return 0;
}
glfwSetWindowTitle("GLFW Application");
for(int i = 0;i < 10; i++) {
table.push_back(i);
}
th_mutex = glfwCreateMutex();
th_1 = glfwCreateThread(Thread_1, NULL);
th_2 = glfwCreateThread(Thread_2, NULL);
while(running)
{
// exit if ESC was pressed or window was closed
running = !glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam( GLFW_OPENED);
}
glfwTerminate();
return 0;
}
我正在工作的项目更大,我有 5 个线程在上面运行,并且同时访问了很多 vector 、 map 、队列。在代码的某处,我尝试做类似的事情:
void GLFWCALL CreateVehicleThread(void* arg) {
int index = (*static_cast<PulseStateByEntrance*>(arg)).index;
double t_initial = (*static_cast<PulseStateByEntrance*>(arg)).initial_time;
double t_final = (*static_cast<PulseStateByEntrance*>(arg)).final_time;
int pulse = (*static_cast<PulseStateByEntrance*>(arg)).pulse;
int nb_entrance = (*static_cast<PulseStateByEntrance*>(arg)).nb_entrance;
int min_time_creation = static_cast<int>(ceil(3600 / pulse));
while((glfwGetTime() - (*static_cast<PulseStateByEntrance*>(arg)).initial_time)
< ((*static_cast<PulseStateByEntrance*>(arg)).final_time - (*static_cast<PulseStateByEntrance*>(arg)).initial_time)) {
double t_elapsed = glfwGetTime() - t_initial;
if(t_elapsed > min_time_creation) {
**int nb_vehicle_per_cycle = static_cast<int>((t_elapsed * pulse)/3600);
glfwLockMutex(th_mutex);
VehicleManager::CreateVehicles(nb_vehicle_per_cycle, nb_entrance);
glfwUnlockMutex(th_mutex);**
t_initial = glfwGetTime();
}
}
}
我将我的 VehicleManager:CreateVehicles() 方法放在锁定/解锁之间的原因是因为在该方法中有这一行:
VehicleManager::vehicles_.push_back(vehicle);
所以我想保护 vector :vehicles_。但是,结果我得到了上面的段错误。甚至还有:
glfwLockMutex(th_mutex);
VehicleManager::vechicles_.push_back(vehicle);
glfwUnlockMutex(th_mutex);
我遇到了同样的段错误。
我希望,我已经清楚地表达了自己的意思,以便您了解我的问题的本质。我想,并非所有人都使用过 GLFW,这就是为什么我给了您第一个基本示例,以便您了解互斥锁如何与这个库一起工作。
谢谢!
最佳答案
你可以包装你的容器,这将使你的代码更容易理解:
template<typename T>
class MultithreadedVector
{
public:
void pushback( T data )
{
glfwLockMutex(m_mutex);
m_container.push_back( data );
glfwUnlockMutex(m_mutex);
}
//then similar for erase etc
private:
std::vector<T> m_container;
GLFWmutex m_mutex;
};
关于C++/GLFW - 使用 Mutex 对象的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/997366/