logo

C++의 멀티스레딩

멀티스레딩은 CPU 활용도를 최대화하기 위해 프로그램의 둘 이상의 부분을 동시에 실행할 수 있는 기능입니다. 이러한 프로그램의 각 부분을 스레드라고 합니다. 따라서 스레드는 프로세스 내의 경량 프로세스입니다.

Verilog 사례 설명

멀티스레딩 지원은 C++11에서 도입되었습니다. C++11 이전에는 다음을 사용해야 했습니다. POSIX 스레드 또는 라이브러리 . 이 라이브러리가 작업을 수행하는 동안 표준 언어 제공 기능 세트가 부족하여 심각한 이식성 문제가 발생했습니다. C++ 11은 이 모든 것을 없애고 우리에게 표준::스레드 . 스레드 클래스 및 관련 함수는 헤더 파일.



통사론:

std::thread thread_object (callable);>

표준::스레드 C++에서 단일 스레드를 나타내는 스레드 클래스입니다. 스레드를 시작하려면 새 스레드 개체를 만들고 호출할 실행 코드(즉, 호출 가능한 개체)를 개체의 생성자에 전달하기만 하면 됩니다. 객체가 생성되면 콜러블에 지정된 코드를 실행하는 새 스레드가 시작됩니다. 콜러블은 다음 다섯 가지 중 하나일 수 있습니다.

  • 함수 포인터
  • 람다 표현식
  • 함수 객체
  • 비정적 멤버 함수
  • 정적 멤버 함수

콜러블을 정의한 후 이를 생성자에 전달합니다.



함수 포인터를 사용하여 스레드 시작하기

함수 포인터는 스레드를 초기화하기 위해 std::thread 생성자에 전달할 호출 가능한 객체일 수 있습니다. 다음 코드 조각은 이를 수행하는 방법을 보여줍니다.

예:

C++






void> foo(param)> {> >Statements;> }> // The parameters to the function are put after the comma> std::>thread> thread_obj(foo, params);>

>

>

람다 표현식을 사용하여 스레드 시작

std::thread 객체는 람다 표현식을 호출 가능 항목으로 사용하여 시작할 수도 있습니다. 다음 코드 조각은 이 작업이 수행되는 방법을 보여줍니다.

예:

C++




// Define a lambda expression> auto> f = [](params)> {> >Statements;> };> // Pass f and its parameters to thread> // object constructor as> std::>thread> thread_object(f, params);>

>

>

함수 객체를 사용하여 스레드 시작하기

C++에서 스레드를 시작하는 데 함수 개체 또는 Functor를 사용할 수도 있습니다. 다음 코드 조각은 수행 방법을 보여줍니다.

예:

C++

정렬 목록 자바




// Define the class of function object> class> fn_object_class {> >// Overload () operator> >void> operator()(params)> >{> >Statements;> >}> }> // Create thread object> std::>thread> thread_object(fn_object_class(), params)>

>

>

메모 : 우리는 항상 콜러블의 매개변수를 스레드 생성자에 대한 인수로 별도로 전달합니다.

비정적 멤버 함수를 사용하여 스레드 시작

클래스의 비정적 멤버 함수를 사용하여 스레드를 시작할 수도 있습니다. 다음 스니펫은 이를 수행하는 방법을 보여줍니다.

C++




// defining clasc> class> Base {> public>:> >// non-static member function> >void> foo(param) { Statements; }> }> // object of Base Class> Base b;> // first parameter is the reference to the functionn> // and second paramter is reference of the object> // at last we have arguments> std::>thread> thread_obj(&Base::foo, &b, params);>

>

로마 숫자 1부터 100까지

>

정적 멤버 함수를 사용하여 스레드 시작

정적 멤버 함수를 사용하여 스레드를 시작할 수도 있습니다.

C++




// defining class> class> Base {> public>:> >// static member function> >static> void> foo(param) { Statements; }> }> // object of Base Class> Base b;> // first parameter is the reference to the function> // and rest are arguments> std::>thread> thread_obj(&Base::foo, params);>

>

Java에서 문자열을 정수로 변환하는 방법
>

스레드가 완료되기를 기다리는 중

스레드가 시작되면 어떤 조치를 취하기 전에 스레드가 완료될 때까지 기다려야 할 수도 있습니다. 예를 들어, 애플리케이션의 GUI를 초기화하는 작업을 스레드에 할당하는 경우 GUI가 제대로 로드되었는지 확인하기 위해 스레드가 완료될 때까지 기다려야 합니다.

스레드를 기다리려면 표준::스레드::조인() 기능. 이 함수는 현재 스레드가 다음으로 식별된 스레드가 나타날 때까지 기다리게 만듭니다. *이것 실행을 마쳤습니다.
예를 들어 스레드 t1이 완료될 때까지 메인 스레드를 차단하려면 다음을 수행합니다.

C++




네트워크와 인터넷
int> main()> {> >// Start thread t1> >std::>thread> t1(callable);> >// Wait for t1 to finish> >t1.join();> >// t1 has finished do other stuff> >Statements;> }>

>

>

멀티스레딩을 위한 완전한 C++ 프로그램

C++ 프로그램은 아래와 같습니다. 기본 함수에서 세 개의 스레드를 시작합니다. 각 스레드는 위에 지정된 호출 가능 개체 중 하나를 사용하여 호출됩니다.

C++




// C++ program to demonstrate> // multithreading using three> // different callables.> #include> #include> using> namespace> std;> // A dummy function> void> foo(>int> Z)> {> >for> (>int> i = 0; i cout << 'Thread using function' ' pointer as callable '; } } // A callable object class thread_obj { public: void operator()(int x) { for (int i = 0; i cout << 'Thread using function' ' object as callable '; } }; // class definition class Base { public: // non-static member function void foo() { cout << 'Thread using non-static member function ' 'as callable' << endl; } // static member function static void foo1() { cout << 'Thread using static member function as ' 'callable' << endl; } }; // Driver code int main() { cout << 'Threads 1 and 2 and 3 ' 'operating independently' << endl; // This thread is launched by using // function pointer as callable thread th1(foo, 3); // This thread is launched by using // function object as callable thread th2(thread_obj(), 3); // Define a Lambda Expression auto f = [](int x) { for (int i = 0; i cout << 'Thread using lambda' ' expression as callable '; }; // This thread is launched by using // lambda expression as callable thread th3(f, 3); // object of Base Class Base b; thread th4(&Base::foo, &b); thread th5(&Base::foo1); // Wait for the threads to finish // Wait for thread t1 to finish th1.join(); // Wait for thread t2 to finish th2.join(); // Wait for thread t3 to finish th3.join(); // Wait for thread t4 to finish th4.join(); // Wait for thread t5 to finish th5.join(); return 0; }>

>

>

출력(기계에 따라 다름)

Threads 1 and 2 and 3 operating independently Thread using function pointer as callable Thread using function pointer as callable Thread using function pointer as callable Thread using non-static member function as callable Thread using function object as callable Thread using function object as callable Thread using function object as callable Thread using lambda expression as callable Thread using lambda expression as callable Thread using lambda expression as callable Thread using static member function as callable>

메모: std::thread 지원으로 프로그램을 컴파일하려면 g++ -std=c++11 -pthread를 사용하세요.