ShovelingLife
A Game Programmer
ShovelingLife
전체 방문자
오늘
어제
  • 분류 전체보기 (1067)
    • 그래픽스 (57)
      • 공통 (19)
      • 수학 물리 (22)
      • OpenGL & Vulkan (1)
      • DirectX (14)
    • 게임엔진 (180)
      • Unreal (69)
      • Unity (100)
      • Cocos2D-X (3)
      • 개인 플젝 (8)
    • 코딩테스트 (221)
      • 공통 (7)
      • 프로그래머스 (22)
      • 백준 (162)
      • LeetCode (19)
      • HackerRank (2)
      • 코딩테스트 알고리즘 (8)
    • CS (235)
      • 공통 (21)
      • 네트워크 (44)
      • OS & 하드웨어 (55)
      • 자료구조 & 알고리즘 (98)
      • 디자인패턴 (6)
      • UML (4)
      • 데이터베이스 (7)
    • 프로그래밍 언어 (346)
      • C++ (167)
      • C# (88)
      • Java (9)
      • Python (33)
      • SQL (30)
      • JavaScript (8)
      • React (7)
    • 그 외 (9)
      • Math (5)
      • 일상 (5)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • Source Code 좌측 상단에 복사 버튼 추가 완료
  • 언리얼 엔진 C++ 빌드시간 단축 꿀팁
  • 게임 업계 코딩테스트 관련
  • 1인칭 시점으로 써내려가는 글들

인기 글

태그

  • 언리얼
  • 문자열
  • c#
  • 티스토리챌린지
  • 클래스
  • 프로그래머스
  • 알고리즘
  • 포인터
  • string
  • 배열
  • 오블완
  • 백준
  • C++
  • C
  • 그래픽스
  • SQL
  • 유니티
  • 함수
  • 파이썬
  • Unity

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ShovelingLife

A Game Programmer

CS/네트워크

Thread 사용법 및 생성

2022. 7. 24. 16:24

thread 생성 방법

  1) C 스타일 thread 생성 (함수 포인트 활용)

      thread(thread로 돌릴 함수, 넘길 인자);

 

  2) Class의 Static 함수를 사용한 Thread 생성

       thread(Class명:thread로 돌릴 함수, 넘길 인자);

      

  3) Class의 멤버 함수를 사용한 Thread 생성

       thread(Class명:thread로 돌릴 함수, Class 생성자, 넘길 인자);

 

  4) lambda 를 사용한 Class 멤버 함수 Thread 생성

      static이 아닌 클래스의 멤버함수를 Thread로 돌릴 수 있다.

 

  5) lambda 를 사용한 Thread 생성

      thread로 돌릴 내용을 바로 생성 한다.

#include <iostream>
#include <thread>

using namespace std;

/*
 * 함수포인트를 사용한 Thread 에제
 * 유의 사항 : default Parametar는 사용 할 수 없다.
 */
void func_type_thread(int count) {
        for(int i=1; i <= count; i++) {
                cout<<"func point type : count "<<i<<endl;
        }
}

/*
 * class내 부의 static 함수화 멤버 함수를 사용한 Thread 예제
 */
class thread_test
{
public:
    static void class_static_func_type_thread(int count) {
        for(int i=1; i <= count; i++) {
                cout<<"class static func type : count "<<i<<endl;
        }
    }

    void class_func_type_thread(int count) {
        for(int i=1; i <= count; i++) {
                cout<<"class func type : count "<<i<<endl;
        }
    }
};

int main() {
        // 1. C 스타일 thread 생성 (함수 포인트 활용)
        thread thread1 = thread(func_type_thread, 10);
        
        // 2. Class의 Static 함수를 사용한 Thread 생성
        thread thread2 = thread(thread_test::class_static_func_type_thread, 10);
        
        // 3. Class의 멤버 함수를 사용한 Thread 생성
        thread thread3 = thread(&thread_test::class_func_type_thread, thread_test(), 10);
        
        // 4. lamda를 사용하여 Class의 멤버 함수를 Thread로 생성
        thread thread4([](int count) {
                        thread_test tt4;
                        tt4.class_func_type_thread(count);
                        }, 10);
                        
        // 5. lambda 를 사용한 Thread 생성
        thread thread5([](int count) {
                        for(int i=1; i <= count; i++) {
                        cout<<"lambda type : count "<<i<<endl;
                        }
                        }, 10);

        thread1.join();
        thread2.join();
        thread3.join();
        thread4.join();
        thread5.join();
        return 0;
}

 

class안에서 Thread 실행 하기

  핵심 

    - 1번 재 인자로 class에서 thread로 돌릴 함수의 주소를 넘긴다.

    - 2번 this 를 넘긴다. (현재 생성된 객체를 넘기는 것을 의미) 

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

2) 비동기로 실행 결과 받기(async 사용)

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

출처 : https://doitnow-man.tistory.com/203

저작자표시 (새창열림)

'CS > 네트워크' 카테고리의 다른 글

TCP와 UDP의 특징과 차이  (0) 2022.11.04
C# 원자적 연산 (Interlocked 클래스)  (0) 2022.07.26
C++ 원자적 연산 (atomic)  (0) 2022.07.26
데드락 (Deadlock) 의미 & 조건  (0) 2022.07.24
멀티 스레드 (Multi Thread) 소스코드  (0) 2022.07.24
    'CS/네트워크' 카테고리의 다른 글
    • C# 원자적 연산 (Interlocked 클래스)
    • C++ 원자적 연산 (atomic)
    • 데드락 (Deadlock) 의미 & 조건
    • 멀티 스레드 (Multi Thread) 소스코드
    ShovelingLife
    ShovelingLife
    Main skill stack => Unity C# / Unreal C++ Studying Front / BackEnd, Java Python

    티스토리툴바