Latest web development tutorials

C ++ 멀티 스레딩

멀티 스레딩은 멀티 태스킹의 전문 형태이며, 멀티 태스킹는 컴퓨터 실행 두 개 이상의 프로그램을 할 수 있습니다. 일반적으로, 멀티 태스킹의 두 가지 유형이 : 프로세스 기반 및 스레드 기반.

  • 프로세스 기반의 멀티 태스킹 프로그램을 동시에 실행된다.
  • 처리 스레드 기반 멀티 태스킹은 동일한 프로그램 단편의 동시 실행된다.

멀티 스레드 프로그램을 동시에 실행할 수있는 두 개 이상의 부품이 포함되어 있습니다. 각 부분에 대한 이러한 프로그램은 각 스레드 실행 별도의 경로를 정의, 스레드라고합니다.

C ++ 멀티 스레드 응용 프로그램에 대한 내장 지원을 포함하지 않습니다. 대신에,이 기능을 제공하는 운영 체제에 전적으로 의존한다.

이 튜토리얼은, 우리가 POSIX는 멀티 쓰레드 C ++ 프로그램을 작성 사용하려면 Linux 운영 체제를 사용하고 있다고 가정합니다. API POSIX 스레드 또는에서는 Pthreads은 같은 FreeBSD의,는 netbsd, GNU / 리눅스, 맥 OS X 및 Solaris로 사용할 수 유닉스 POSIX 시스템의 여러 유형에 제공 할 수있다.

스레드를 생성

다음 프로그램, 우리는 POSIX 쓰레드를 생성하는 데 사용할 수있다 :

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

여기가 pthread_create는 새로운 스레드를 생성하고 실행합니다.다음은 매개 변수에 대한 설명입니다 :

参数 描述
thread 指向线程标识符指针。
attr 一个不透明的属性对象,可以被用来设置线程属性。您可以指定线程属性对象,也可以使用默认值 NULL。
start_routine 线程运行函数起始地址,一旦线程被创建就会执行。
arg 运行函数的参数。它必须通过把引用作为指针强制转换为 void 类型进行传递。如果没有传递参数,则使用 NULL。

스레드가 성공적으로 생성되면 0이 반환 값이 스레드를 생성하지 못했음을 나타내는 경우,이 함수는 0을 반환한다.

스레드 종료

다음 절차를 사용하여, 우리는 POSIX 스레드를 종료하는 데 사용할 수 있습니다 :

#include <pthread.h>
pthread_exit (status) 

여기서,는 pthread_exit 명시 적으로 스레드를 종료하는 데 사용됩니다.작업이 스레드 후 계속 존재하지 않고 완료되면 정상적인 상황에서,는 pthread_exit () 함수가 호출됩니다.

는 IT가 만든 스레드가 끝나기 전에 () 주, 그리고는 pthread_exit을 종료 할 경우 (), 다음 다른 스레드가 계속 실행됩니다. 그렇지 않으면 끝 () 주 자동으로 종료 될 것이다.

다음의 간단한 예제 코드가 pthread_create를 () 함수는 다섯 스레드, 각 출력 생성 사용 "w3big 안녕하세요!"

#include <iostream>
// 必须的头文件是
#include <pthread.h>

using namespace std;

#define NUM_THREADS 5

// 线程的运行函数
void* say_hello(void* args)
{
    cout << "Hello w3big!" << endl;
}

int main()
{
    // 定义线程的 id 变量,多个变量使用数组
    pthread_t tids[NUM_THREADS];
    for(int i = 0; i < NUM_THREADS; ++i)
    {
        //参数依次是:创建的线程id,线程参数,调用的函数,传入的函数参数
        int ret = pthread_create(&tids[i], NULL, say_hello, NULL);
        if (ret != 0)
        {
           cout << "pthread_create error: error_code=" << ret << endl;
        }
    }
    //等各个线程退出后,进程才结束,否则进程强制结束了,线程可能还没反应过来;
    pthread_exit(NULL);
}

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

$ g++ test.cpp -lpthread -o test.o

이제, 프로그램의 실행은 다음과 같은 결과를 생성 할 것이다 :

$ ./test.o
Hello w3big!
Hello w3big!
Hello w3big!
Hello w3big!
Hello w3big!

다음의 간단한 예제 코드가 pthread_create를 () 함수는 다섯 스레드를 생성하고 입력 매개 변수를 수신합니다. 각 스레드는 스레드를 종료)는 "w3big 안녕하세요!"메시지를 출력하고, 수신 된 매개 변수를 출력 한 후 (는 pthread_exit를 호출합니다.

//文件名:test.cpp

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

using namespace std;

#define NUM_THREADS     5

void *PrintHello(void *threadid)
{  
   // 对传入的参数进行强制类型转换,由无类型指针变为整形数指针,然后再读取
   int tid = *((int*)threadid);
   cout << "Hello w3big! 线程 ID, " << tid << endl;
   pthread_exit(NULL);
}

int main ()
{
   pthread_t threads[NUM_THREADS];
   int indexes[NUM_THREADS];// 用数组来保存i的值
   int rc;
   int i;
   for( i=0; i < NUM_THREADS; i++ ){      
      cout << "main() : 创建线程, " << i << endl;
      indexes[i] = i; //先保存i的值
      // 传入的时候必须强制转换为void* 类型,即无类型指针        
      rc = pthread_create(&threads[i], NULL, 
                          PrintHello, (void *)&(indexes[i]));
      if (rc){
         cout << "Error:无法创建线程," << rc << endl;
         exit(-1);
      }
   }
   pthread_exit(NULL);
}

이제 컴파일하고 다음과 같은 결과를 얻을 프로그램을 실행 :

$ g++ test.cpp -lpthread -o test.o
$ ./test.o
main() : 创建线程, 0
main() : 创建线程, 1
main() : 创建线程, 2
main() : 创建线程, 3
main() : 创建线程, 4
Hello w3big! 线程 ID, 4
Hello w3big! 线程 ID, 3
Hello w3big! 线程 ID, 2
Hello w3big! 线程 ID, 1
Hello w3big! 线程 ID, 0

스레드에 매개 변수를 전달

이 예는 여러 매개 변수 구조를 전달하는 방법을 보여줍니다. 이 빈 공간을 가리키는 때문에 다음 예에서와 같이 당신은, 스레드 콜백에서 모든 유형의 데이터를 전달할 수 있습니다 :

#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);
}

상기 코드는 컴파일되고 실행될 때, 다음과 같은 결과를

$ g++ -Wno-write-strings test.cpp -lpthread -o test.o
$ ./test.o
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) 

지정된 threadid 스레드가 종료 될 때까지 위해 pthread_join () 서브 루틴 호출 프로그램을 방해. 당신이 스레드를 만들 때 속성이이 (조인) 또는 (분리) 분리 연결되어 있는지 여부를 정의합니다. 연결할 수있는 접속 될 수있는 스레드를 생성만을 정의한다. 생성 스레드 같이 분리 정의되는 경우,이 접속 될 수 없다.

이 예는 완료 ​​스레드를 기다릴 위해 pthread_join () 함수를 사용하는 방법을 보여줍니다.

#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;

   // 初始化并设置线程为可连接的(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], NULL, wait, (void *)i );
      if (rc){
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }

   // 删除属性,并等待其他线程
   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 : 4  ...exiting 
Sleeping in thread 
Thread with id : 3  ...exiting 
Sleeping in thread 
Thread with id : 2  ...exiting 
Sleeping in thread 
Thread with id : 1  ...exiting 
Sleeping in thread 
Thread with id : 0  ...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.