遍历向量,而其他线程可能会修改它
Iterating through a vector while other threads may modify it
我在多线程方面没有经验,但是在套接字编程中我需要它。我的问题是,我需要遍历 class 的静态向量,但是,当我这样做时,其他线程会从该向量中删除元素,这会导致我的程序崩溃。我假设我需要以某种方式锁定矢量,但我不知道如何锁定。我找到的唯一解决方案似乎是 Windows 特定的 (Concurrency::concurrent_vector)。这是我的代码:
#include <pthread.h>
#include <thread>
#include <mutex>
std::vector<User*> User::users;
std::mutex mtx;
int main() {
//...
mtx.lock();
for (int i = 0; i < User::users.size(); ++i) {
User::users.at(i)->stop = true;
User::users.at(i)->shutdownSocket();
}
mtx.unlock();
}
这貌似没有锁定vector。我在 Ubuntu 上使用 CLion。我怎样才能安全地做到这一点?
编辑:我在访问向量的所有地方都包含了 mtx.lock() 和 unlock() 。我已经仔细检查过了。
我使用一个在 main.cpp 中声明的互斥体和一个在 User.h 中声明的互斥体有关系吗?我必须对同一个向量使用同一个互斥体吗?
Does it matter that I use one mutex declared in my main.cpp and one in User.h? Do I have to use the same mutex for the same vector?
是的,是的。
您使用一个互斥量来跨多个线程同步资源。
不同的互斥量相互不了解。
互斥体就像一组交通信号灯。当一个 post 变红时,另一个变绿。那是因为它们由马路拐角处的同一个机柜控制,它知道如何在正确的时间以正确的顺序让两个 post 同步发生变化。沿街的红绿灯由完全不同的机柜控制,控制不同的路口,不能帮你管理第一个路口的交通;如果你假装它确实如此,你最终会遇到严重的崩溃。
我在多线程方面没有经验,但是在套接字编程中我需要它。我的问题是,我需要遍历 class 的静态向量,但是,当我这样做时,其他线程会从该向量中删除元素,这会导致我的程序崩溃。我假设我需要以某种方式锁定矢量,但我不知道如何锁定。我找到的唯一解决方案似乎是 Windows 特定的 (Concurrency::concurrent_vector)。这是我的代码:
#include <pthread.h>
#include <thread>
#include <mutex>
std::vector<User*> User::users;
std::mutex mtx;
int main() {
//...
mtx.lock();
for (int i = 0; i < User::users.size(); ++i) {
User::users.at(i)->stop = true;
User::users.at(i)->shutdownSocket();
}
mtx.unlock();
}
这貌似没有锁定vector。我在 Ubuntu 上使用 CLion。我怎样才能安全地做到这一点?
编辑:我在访问向量的所有地方都包含了 mtx.lock() 和 unlock() 。我已经仔细检查过了。
我使用一个在 main.cpp 中声明的互斥体和一个在 User.h 中声明的互斥体有关系吗?我必须对同一个向量使用同一个互斥体吗?
Does it matter that I use one mutex declared in my main.cpp and one in User.h? Do I have to use the same mutex for the same vector?
是的,是的。
您使用一个互斥量来跨多个线程同步资源。
不同的互斥量相互不了解。
互斥体就像一组交通信号灯。当一个 post 变红时,另一个变绿。那是因为它们由马路拐角处的同一个机柜控制,它知道如何在正确的时间以正确的顺序让两个 post 同步发生变化。沿街的红绿灯由完全不同的机柜控制,控制不同的路口,不能帮你管理第一个路口的交通;如果你假装它确实如此,你最终会遇到严重的崩溃。