Cplusplus 简明教程

C++ Multithreading

多线程化是一种特殊形式的多任务处理,而多任务处理是一种允许计算机同时运行两个或更多程序的功能。通常,有多种类型:基于进程和基于线程。

Multithreading is a specialized form of multitasking and a multitasking is the feature that allows your computer to run two or more programs concurrently. In general, there are two types of multitasking: process-based and thread-based.

基于进程的多任务处理处理程序的并发执行。基于线程的多任务处理处理同一程序的片段并发执行。

Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the concurrent execution of pieces of the same program.

多线程程序包含可并发运行的两个或多个部分。该程序的每个部分称为一个线程,每个线程定义一条独立的执行路径。

A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.

在 C++ 11 之前,没有对多线程应用程序的内置支持。相反,它完全依赖于操作系统提供此功能。

Before C++ 11, there is no built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature.

本教程假定你在 Linux 操作系统上工作,并且我们将使用 POSIX 编写多线程 C++ 程序。POSIX 线程或 Pthreads 提供可在许多类 Unix 的 POSIX 系统(例如 FreeBSD、NetBSD、GNU/Linux、Mac OS X 和 Solaris)中使用的 API。

This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded C++ program using POSIX. POSIX Threads, or Pthreads provides API which are available on many Unix-like POSIX systems such as FreeBSD, NetBSD, GNU/Linux, Mac OS X and Solaris.

Creating Threads

以下例程用于创建 POSIX 线程−

The following routine is used to create a POSIX thread −

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

此处, pthread_create 创建新线程并使其可执行。此例程可以从代码中的任何位置多次调用。以下是参数说明−

Here, pthread_create creates a new thread and makes it executable. This routine can be called any number of times from anywhere within your code. Here is the description of the parameters −

Sr.No

Parameter & Description

1

thread An opaque, unique identifier for the new thread returned by the subroutine.

2

attr An opaque attribute object that may be used to set thread attributes. You can specify a thread attributes object, or NULL for the default values.

3

start_routine The C++ routine that the thread will execute once it is created.

4

arg A single argument that may be passed to start_routine. It must be passed by reference as a pointer cast of type void. NULL may be used if no argument is to be passed.

进程可以创建的最大线程数取决于实现。创建后,线程是同级线程,可以创建其他线程。线程之间没有隐含的层次结构或依赖关系。

The maximum number of threads that may be created by a process is implementation dependent. Once created, threads are peers, and may create other threads. There is no implied hierarchy or dependency between threads.

Terminating Threads

我们使用以下例程终止 POSIX 线程−

There is following routine which we use to terminate a POSIX thread −

#include <pthread.h>
pthread_exit (status)

此处, pthread_exit 用于显式退出线程。通常,pthread_exit() 例程在某个线程完成后且不再需要存在时才会调用。

Here pthread_exit is used to explicitly exit a thread. Typically, the pthread_exit() routine is called after a thread has completed its work and is no longer required to exist.

如果 main() 在它创建的线程之前完成,并且退出时使用的是 pthread_exit(),则其他线程仍将继续执行。否则,它们将在 main() 完成时自动终止。

If main() finishes before the threads it has created, and exits with pthread_exit(), the other threads will continue to execute. Otherwise, they will be automatically terminated when main() finishes.

Example

此简单示例代码使用 pthread_create() 例程创建 5 个线程。每个线程打印一个“Hello World!”消息,然后通过调用 pthread_exit() 终止。

This simple example code creates 5 threads with the pthread_create() routine. Each thread prints a "Hello World!" message, and then terminates with a call to 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 库编译以下程序,如下所示−

Compile the following program using -lpthread library as follows −

$gcc test.cpp -lpthread

现在,执行您的程序,该程序产生以下输出 −

Now, execute your program which gives the following output −

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

Passing Arguments to Threads

此示例展示如何通过结构传递多个参数。您可在线程回调中传递任何数据类型,因为它指向空值,如以下示例中说明 −

This example shows how to pass multiple arguments via a structure. You can pass any data type in a thread callback because it points to void as explained in the following example −

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

编译并执行上述代码后,将产生以下结果 −

When the above code is compiled and executed, it produces the following result −

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

Joining and Detaching Threads

以下两个例程可用于连接或分离线程 −

There are following two routines which we can use to join or detach threads −

pthread_join (threadid, status)
pthread_detach (threadid)

pthread_join() 子例程会阻塞调用线程,直到指定的“threadid”线程结束。当创建了一个线程时,其一个属性用于定义它是可链接还是分离的。只有作为可连接的线程创建的线程才能被连接。如果一个线程作为分离的线程创建,它永远不能被连接。

The pthread_join() subroutine blocks the calling thread until the specified 'threadid' thread terminates. When a thread is created, one of its attributes defines whether it is joinable or detached. Only threads that are created as joinable can be joined. If a thread is created as detached, it can never be joined.

此示例会演示如何使用 Pthread 连接例程等待线程完成。

This example demonstrates how to wait for thread completions by using the Pthread join routine.

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

编译并执行上述代码后,将产生以下结果 −

When the above code is compiled and executed, it produces the following result −

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.