C++并发(C++11)-03 向线程传递参数


普通传参

#include <iostream>
#include <string>
#include <thread>
using namespace std;

void func(string m) {
  cout << "&m:" << &m;
  cout << endl;
}

int main() {
  string s = "xxxx";
  cout << "&s:" << &s << endl;
  thread t(func, s);
  t.join();
  return 0;
}

 

 线程会将参数拷贝后访问

引用传参:常量引用

#include <iostream>
#include <string>
#include <thread>
using namespace std;

void func(const string& m) {
  cout << "&m:" << &m;
  cout << endl;
}

int main() {
  string s = "xxxx";
  cout << "&s:" << &s << endl;
  thread t(func, s);
  t.join();
  return 0;
}

 

 线程会将参数拷贝后访问

引用传参:非常量引用

#include <iostream>
#include <string>
#include <thread>
using namespace std;

void func(string& m) {
  cout << "&m:" << &m;
  cout << endl;
}

int main() {
  string s = "xxxx";
  cout << "&s:" << &s << endl;
  thread t(func, ref(s));
  t.join();
  return 0;
}

 

 此时要用到std::ref()将参数转换成引用形式,线程访问的变量与参数变量为同一地址。

指针传参

#include <iostream>
#include <string>
#include <thread>
using namespace std;

void func(string* m) {
  cout << "m:" << m;
  cout << endl;
  *m = "yyy";
}

int main() {
  string* s = new string("xxx");
  cout << "s:" << s << endl;
  thread t(func, s);
  t.join();
  cout << "s:" << *s << endl;
  return 0;
}

 

 此时,线程中的指针与参数指针指向同一地址。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM