C + + Multithreading

Source: Internet
Author: User
Tags posix
Multithreading is a special form of multitasking, and multitasking allows a computer to run two or more programs at the same time. In general, there are two types of multitasking: process-based and thread-based.

Process-based multitasking is the concurrent execution of a program.

A thread-based multitasking process is a concurrent execution of fragments of the same program.

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

C + + does not contain any built-in support for multithreaded applications. Instead, it relies entirely on the operating system to provide this functionality.

This tutorial assumes that you are using a Linux operating system and that we are using POSIX to write multithreaded C + + programs. The APIs provided by POSIX Threads or Pthreads are available on a variety of Unix-like POSIX systems, such as FreeBSD, NetBSD, Gnu/linux, Mac OS X, and Solaris.

Creating Threads

In the following program, we can use it to create a POSIX thread:

#include <pthread.h>pthread_create (thread, attr, Start_routine, Arg)

Here, Pthread_create creates a new thread and makes it executable. Here is a description of the parameters:

parameters description
thread points to the thread identifier pointer.
attr start_routine The thread runs the start address of the function and executes as soon as the thread is created.
arg The parameters of the run function. It must be passed by casting the reference as a pointer to void type. If no arguments are passed, NULL is used.

When creating a line Cheng, the function returns 0, and if the return value is not 0, the creation thread fails.

Terminating a thread

Using the following program, we can use it to terminate a POSIX thread:

#include <pthread.h>pthread_exit (status)

Here, Pthread_exit is used to explicitly exit a thread. Typically, the Pthread_exit () function is called when the thread finishes working without needing to continue.

If main () ends before the thread it creates and exits through Pthread_exit (), the other threads continue to execute. Otherwise, they will be automatically terminated at the end of Main ().

Instance

The following simple instance code creates 5 threads using the Pthread_create () function, and each thread outputs "Hello runoob! ":

#include <iostream>//Required header file is # include <pthread.h>using namespace std; #define NUM_THREADS 5//thread run function void* Say_hello (void* args) {    cout << "Hello runoob! "<< Endl;} int main () {    //define thread ID variable, multiple variables use array    pthread_t tids[num_threads];    for (int i = 0; i < num_threads; ++i)    {        ///Parameters are: Created thread ID, thread parameter, function called, incoming function parameter        int ret = pthread_create (& Tids[i], NULL, Say_hello, NULL);        if (ret! = 0)        {           cout << "Pthread_create error:error_code=" << ret << Endl;        }    }    After each thread exits, the process ends, or the process forces the end, and the thread may not yet respond;    pthread_exit (NULL);}

Compile the following program using the-lpthread library:

$ g++ Test.cpp-lpthread-o TEST.O

Now, executing the program will produce the following results:

$./test.ohello runoob! Hello runoob! Hello runoob! Hello runoob! Hello runoob!

The following simple instance code uses the Pthread_create () function to create 5 threads and receive incoming arguments. Each thread prints a "Hello runoob!" message, outputs the received parameters, and then calls Pthread_exit () to terminate the thread.

File name: Test.cpp#include <iostream> #include <cstdlib> #include <pthread.h>using namespace std;# Define Num_threads     5void *printhello (void *threadid) {     //coercion type conversion of passed arguments, changed from untyped pointer to shaped number pointer, and then read   int tid = * (( int*) threadid);   cout << "Hello runoob! Thread ID, "<< tid << Endl;   Pthread_exit (NULL);} int main () {   pthread_t threads[num_threads];   int indexes[num_threads];//An array to hold the value of i   int RC;   int i;   for (i=0; i < num_threads; i++) {            cout << "main (): Create Thread," << i << Endl;      Indexes[i] = i; The value of I is first saved      //passed in must be cast to the void* type, i.e. the untyped pointer              rc = pthread_create (&threads[i], NULL,                           Printhello, (void * ) & (Indexes[i]);      if (RC) {         cout << "Error: Unable to create thread," << RC << Endl;         Exit ( -1);      }   }   Pthread_exit (NULL);}

Compiling and executing the program now produces the following results:

$ g++ test.cpp-lpthread-o test.o$./TEST.O

Main (): Create Thread, 0main (): Create Thread, 1main (): Create Thread, 2main (): Create Thread, 3main (): Create Thread, 4Hello runoob! Thread ID, 4Hello runoob! Thread ID, 3Hello runoob! Thread ID, 2Hello runoob! Thread ID, 1Hello runoob! Thread ID, 0

Passing parameters to threads

This example demonstrates how to pass multiple parameters through a struct. You can pass any data type in the thread callback because it points to void, as shown in the following example:

#include <iostream> #include <cstdlib> #include <pthread.h>using namespace std; #define Num_threads 5s   truct 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 results:

$ g++-wno-write-strings test.cpp-lpthread-o test.o$./test.omain (): Creating Thread, 0main (): Creating Thread, 1main ( ): Creating Thread, 2main (): Creating Thread, 3main (): Creating Thread, 4Thread id:3 message:this is Messagethread Id:2 Message:this is Messagethread id:0 message:this are messagethread id:1 message:this is Messagethread

Id:4 Message:this is Message

Connecting and detaching Threads

We can use the following two functions to connect or detach a thread:

Pthread_join (ThreadID, status) Pthread_detach (ThreadID)

The Pthread_join () subroutine blocks the calling program until the specified ThreadID thread terminates. When a thread is created, one of its properties defines whether it is connected (joinable) or separable (detached). Only threads that are defined as being connected at creation time can be connected. If a thread is created as separable, it can never be connected.

This example demonstrates how to use the Pthread_join () function to wait for the thread to complete.

#include <iostream> #include <cstdlib> #include <pthread.h> #include <unistd.h>using namespace   STD; #define Num_threads 5void *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;   Initializes and sets the thread to be connected (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);   }}//delete properties and wait for other threads to Pthread_attr_destroy (&AMP;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 results:

Main (): Creating Thread, 0main (): Creating Thread, 1main (): Creating Thread, 2main (): Creating Thread, 3main (): creat ing thread, 4Sleeping in thread thread with Id:4  ... exiting sleeping in thread thread with Id:3  ... exiting Sle Eping 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:0main:completed thread id:1  Exiting with status:0main:completed thread Id:2  exiting with status:0main:completed thread Id:3  exiting with status:0main:completed thread Id:4  exiting with Status:0main:program exiting.

The above is the C + + multi-threading content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.