为什么线程对类变量所做的更改没有影响?
why thread has no effect on change made on class variable?
#include <iostream>
#include <thread>
using namespace std;
struct A{
void Add(){
++val;
}
int val = 0;
};
int main(){
A a;
thread t(&A::Add,a);
t.join();
std::cout << a.val << std::endl;
}
为什么最终将 +1 添加到值的线程的执行没有效果?std::cout 只是零。我期待 1。
您正在按值传递a
,因此线程获得自己的私有副本,该副本不同于main
中的a
- 然后线程修改副本,当线程死亡时,该对象随之死亡,并且找不到对它的更改。main
中的a
永远不会修改,因此它保留其原始值。如果要从线程中更改main
中的a
,则需要传递引用或指针。
如果要从多个线程访问变量,您可能还想阅读同步和原子。
正如@JesperJuhl所说,您正在传递a
的副本,因此 main 的变量永远不会被修改,但除此之外,引用不能传递给其他线程。线程的参数总是按值传递的,因此,您需要传递指针或reference_wrapper
,这允许传递引用,但包装在可复制的对象中:
#include <iostream>
#include <thread>
using namespace std;
struct A{
void Add(){
++val;
}
int val = 0;
};
int main(){
A a;
// Passing a reference_wrapper is the standard way.
// Passing a pointer would imply to change your method signature
// and implementation if it were a free function instead of a
// class member function.
// In your specific case it is irrelevant though.
thread t(&A::Add,std::ref(a));
// or thread t(&A::Add,&a);
t.join();
std::cout << a.val << std::endl;
}
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 用C++中的std::condition_variable将线程置于死锁中会有风险吗
- 是否有必要获取锁并在不需要唤醒线程时通知condition_variable?
- 处理影响跨不同线程共享对象的定时回调的最佳方法是什么?
- 有没有办法在另一个函数中加入线程?(即超出其自身范围)
- 我有一个线程 1:EXC_BAD_ACCESS(代码 = 1,地址 = 0x8)错误.我认为这是由于内存管理不好.我可以
- 对于 ~95% 写入/5% 读取线程安全的无序列图,有没有一个简单的解决方案?
- 线程和互斥锁的使用有什么问题
- Vulkan默认情况下已经有多线程了吗
- 有没有办法获取线程使用的内核?
- 为什么线程对类变量所做的更改没有影响?
- 在给定时间段内,线程执行的指令数量是否有最小数量?
- 如何让线程等待对象完全破坏?(对象也有一个线程)?
- 在 C++11 线程中,std::mutex 对内存可见性有什么保证?
- 如何判断是否有另一个线程试图保持互斥锁?
- if 语句仅在前面有调试 cout 行(C 中的多线程)时才通过
- 了解索引以及块中有多少线程
- 如果没有线程阻塞信号,并且有一个线程处于"sigwait()"中,是否可以保证被阻塞的线程将接收下一
- 完成的线程是否对 winapi 中的主程序有影响
- Libuv -如何保持默认循环运行,直到程序中至少有一个线程存活