thread arguments

김대익·2022년 3월 24일
0
#include <iostream>
#include <thread>
#include <string>

void fn(int a, std::string & s) {
	std::cout << a << s << std::endl;
}

int main() {
	int num = 42;
    std::string s = "nocope";
    std::thread t1(fn, num, std::ref(s));
    t1.join();
}

thread 내부에서 실행되는 함수의 인수는
std::thread의 2번째 인수부터 들어간다

그런데 fn 인수는 value로 받고있기 때문에 copy가 일어나고 있다.
copy이다보니 값의 크기에 따라 무거운 동작일 수도 있다
그러므로 reference로 옮기는 것이 좋다

이 때 reference로 가는 변수나 객체의 life cycle을 주의해서 고려해야한다.

따라서 threadCaller에서 t를 join해줘야한다


0개의 댓글