산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> C 언어

C++ 멀티스레딩

멀티스레딩은 멀티태스킹의 특수한 형태이며 멀티태스킹은 컴퓨터에서 두 개 이상의 프로그램을 동시에 실행할 수 있는 기능입니다. 일반적으로 멀티태스킹에는 프로세스 기반과 스레드 기반의 두 가지 유형이 있습니다.

프로세스 기반 멀티태스킹은 프로그램의 동시 실행을 처리합니다. 스레드 기반 멀티태스킹은 동일한 프로그램의 일부를 동시에 실행하는 것을 처리합니다.

다중 스레드 프로그램은 동시에 실행할 수 있는 두 개 이상의 부분을 포함합니다. 이러한 프로그램의 각 부분을 스레드라고 하며 각 스레드는 별도의 실행 경로를 정의합니다.

C++에는 다중 스레드 응용 프로그램에 대한 기본 제공 지원이 포함되어 있지 않습니다. 대신 이 기능을 제공하는 운영 체제에 전적으로 의존합니다.

이 튜토리얼은 사용자가 Linux OS에서 작업 중이고 POSIX를 사용하여 다중 스레드 C++ 프로그램을 작성한다고 가정합니다. POSIX 스레드 또는 Pthreads는 FreeBSD, NetBSD, GNU/Linux, Mac OS X 및 Solaris와 같은 많은 Unix 계열 POSIX 시스템에서 사용할 수 있는 API를 제공합니다.

스레드 생성

다음 루틴은 POSIX 스레드를 생성하는 데 사용됩니다 -

#include <pthread.h>
pthread_create (thread, attr, start_routine, arg) 

여기 pthread_create 새 스레드를 만들고 실행 가능하게 만듭니다. 이 루틴은 코드 내 어디에서나 여러 번 호출할 수 있습니다. 다음은 매개변수에 대한 설명입니다. -

Sr.No 매개변수 및 설명
1

스레드

서브루틴에서 반환된 새 스레드에 대한 불투명하고 고유한 식별자입니다.

2

속성

스레드 속성을 설정하는 데 사용할 수 있는 불투명한 속성 개체입니다. 스레드 속성 개체를 지정하거나 기본값으로 NULL을 지정할 수 있습니다.

3

start_routine

스레드가 생성되면 실행할 C++ 루틴입니다.

4

인수

start_routine에 전달할 수 있는 단일 인수입니다. void 유형의 포인터 캐스트로 참조로 전달되어야 합니다. 인수가 전달되지 않으면 NULL을 사용할 수 있습니다.

프로세스에서 생성할 수 있는 최대 스레드 수는 구현에 따라 다릅니다. 스레드는 일단 생성되면 피어이며 다른 스레드를 생성할 수 있습니다. 스레드 간에 암시적 계층 또는 종속성이 없습니다.

스레드 종료

POSIX 스레드를 종료하는 데 사용하는 다음 루틴이 있습니다. -

#include <pthread.h>
pthread_exit (status) 

여기 pthread_exit 스레드를 명시적으로 종료하는 데 사용됩니다. 일반적으로 pthread_exit() 루틴은 스레드가 작업을 완료하고 더 이상 존재할 필요가 없는 후에 호출됩니다.

main()이 생성된 스레드보다 먼저 종료되고 pthread_exit()로 종료되면 다른 스레드가 계속 실행됩니다. 그렇지 않으면 main()이 종료될 때 자동으로 종료됩니다.

이 간단한 예제 코드는 pthread_create() 루틴을 사용하여 5개의 스레드를 만듭니다. 각 스레드는 "Hello World!"를 인쇄합니다. 메시지를 보낸 다음 pthread_exit() 호출로 종료됩니다.

#include <iostream>
#include <cstdlib>
#include <pthread.h>

using namespace std;

#define NUM_THREADS 5

void *PrintHello(void *threadid) {
   long tid;
   tid = (long)threadid;
   cout << "Hello World! Thread ID, " << tid << endl;
   pthread_exit(NULL);
}

int main () {
   pthread_t threads[NUM_THREADS];
   int rc;
   int i;
   
   for( i = 0; i < NUM_THREADS; i++ ) {
      cout << "main() : creating thread, " << i << endl;
      rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i);
      
      if (rc) {
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }
   pthread_exit(NULL);
}

다음과 같이 -lpthread 라이브러리를 사용하여 다음 프로그램을 컴파일하십시오 -

$gcc test.cpp -lpthread

이제 다음 출력을 제공하는 프로그램을 실행하십시오 -

main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Hello World! Thread ID, 0
Hello World! Thread ID, 1
Hello World! Thread ID, 2
Hello World! Thread ID, 3
Hello World! Thread ID, 4

스레드에 인수 전달

이 예제는 구조를 통해 여러 인수를 전달하는 방법을 보여줍니다. 다음 예제에서 설명한 대로 void를 가리키기 때문에 스레드 콜백에서 모든 데이터 유형을 전달할 수 있습니다.

#include <iostream>
#include <cstdlib>
#include <pthread.h>

using namespace std;

#define NUM_THREADS 5

struct thread_data {
   int  thread_id;
   char *message;
};

void *PrintHello(void *threadarg) {
   struct thread_data *my_data;
   my_data = (struct thread_data *) threadarg;

   cout << "Thread ID : " << my_data->thread_id ;
   cout << " Message : " << my_data->message << endl;

   pthread_exit(NULL);
}

int main () {
   pthread_t threads[NUM_THREADS];
   struct thread_data td[NUM_THREADS];
   int rc;
   int i;

   for( i = 0; i < NUM_THREADS; i++ ) {
      cout <<"main() : creating thread, " << i << endl;
      td[i].thread_id = i;
      td[i].message = "This is message";
      rc = pthread_create(&threads[i], NULL, PrintHello, (void *)&td[i]);
      
      if (rc) {
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }
   pthread_exit(NULL);
}

위의 코드를 컴파일하고 실행하면 다음과 같은 결과가 생성됩니다. -

main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Thread ID : 3 Message : This is message
Thread ID : 2 Message : This is message
Thread ID : 0 Message : This is message
Thread ID : 1 Message : This is message
Thread ID : 4 Message : This is message

스레드 결합 및 분리

스레드를 결합하거나 분리하는 데 사용할 수 있는 다음 두 가지 루틴이 있습니다. -

pthread_join (threadid, status) 
pthread_detach (threadid) 

pthread_join() 서브루틴은 지정된 'threadid' 스레드가 종료될 때까지 호출 스레드를 차단합니다. 스레드가 생성되면 해당 속성 중 하나가 스레드가 결합 가능한지 분리 가능한지를 정의합니다. 조인 가능으로 생성된 스레드만 조인할 수 있습니다. 스레드가 분리된 상태로 생성되면 결합할 수 없습니다.

이 예는 Pthread 조인 루틴을 사용하여 스레드 완료를 기다리는 방법을 보여줍니다.

#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>

using namespace std;

#define NUM_THREADS 5

void *wait(void *t) {
   int i;
   long tid;

   tid = (long)t;

   sleep(1);
   cout << "Sleeping in thread " << endl;
   cout << "Thread with id : " << tid << "  ...exiting " << endl;
   pthread_exit(NULL);
}

int main () {
   int rc;
   int i;
   pthread_t threads[NUM_THREADS];
   pthread_attr_t attr;
   void *status;

   // Initialize and set thread joinable
   pthread_attr_init(&attr);
   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

   for( i = 0; i < NUM_THREADS; i++ ) {
      cout << "main() : creating thread, " << i << endl;
      rc = pthread_create(&threads[i], &attr, wait, (void *)i );
      if (rc) {
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }

   // free attribute and wait for the other threads
   pthread_attr_destroy(&attr);
   for( i = 0; i < NUM_THREADS; i++ ) {
      rc = pthread_join(threads[i], &status);
      if (rc) {
         cout << "Error:unable to join," << rc << endl;
         exit(-1);
      }
      cout << "Main: completed thread id :" << i ;
      cout << "  exiting with status :" << status << endl;
   }

   cout << "Main: program exiting." << endl;
   pthread_exit(NULL);
}

위의 코드를 컴파일하고 실행하면 다음과 같은 결과가 생성됩니다. -

main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Sleeping in thread
Thread with id : 0 .... exiting
Sleeping in thread
Thread with id : 1 .... exiting
Sleeping in thread
Thread with id : 2 .... exiting
Sleeping in thread
Thread with id : 3 .... exiting
Sleeping in thread
Thread with id : 4 .... exiting
Main: completed thread id :0  exiting with status :0
Main: completed thread id :1  exiting with status :0
Main: completed thread id :2  exiting with status :0
Main: completed thread id :3  exiting with status :0
Main: completed thread id :4  exiting with status :0
Main: program exiting.

C 언어

  1. C++ 연산자
  2. C++ 주석
  3. C++ 클래스 템플릿
  4. C++ 개요
  5. C++ 상수/리터럴
  6. C++의 연산자
  7. C++의 숫자
  8. C++ 참조
  9. C++ 템플릿
  10. C++ 멀티스레딩