Wu Yuxiong - born natural C ++ language study notes: C ++ multithreading

Multithreading is a specialized form of multi-tasking, multi-tasking allows let the computer run two or more programs. In general, two types of multitasking: process-based and thread-based. 
Process-based multitasking is the concurrent execution of the program. 
Based on multi-task processing thread is executed concurrently fragment of the same program. 
Multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called threads, each defining a single execution path. 
Creating a POSIX threads: 
#include <pthread.h> 
pthread_create (the Thread, attr, start_routine, Arg) 
here, pthread_create creates a new thread and make it executable. The following is a description of the parameters: 
Thread pointers pointing thread identifier. 
attr an opaque object attribute, the attribute may be used to set the thread. You can specify a thread attributes object, you can also use the default value is NULL. 
start_routine thread running function start address, it will be executed once the thread is created. 
Parameters arg run function. It must be incorporated by the pointer cast void for delivery type. If you do not pass parameters, use NULL. 
When you create a thread successfully, the function returns 0 , if the return value is not 0 then the failure to create threads.
Terminating a POSIX threads: 
#include <pthread.h> 
the pthread_exit (Status) 
Here, pthread_exit used to explicitly quit a thread. Typically, pthread_exit () function is called when there is no need to continue the work after the completion of the thread. 
If the main () is the thread that it created before the end, and () to exit through pthread_exit, the other threads will continue to execute. Otherwise, they will () is automatically terminated at the end of main.
The following simple example code uses pthread_create () function creates 5 threads, each thread output " the Hello Runoob! " : 
#Include <iostream>
 // necessary header files 
#include <pthread.h> a using namespace std; #define . 5 NUM_THREADS // running thread function void * say_hello ( void * args) 
{ 
    COUT << " the Hello Runoob! " << endl;
     return 0 ; 
} int main () 
{ // definition of variable thread id, a plurality of variables array
 
 
 

 

 
 

    
    TIDS pthread_t [NUM_THREADS];
     for ( int I = 0 ; I <NUM_THREADS; ++ I) 
    { 
        // parameters are: the thread id, thread parameters, create function call, passing function parameters 
        int RET = pthread_create ( & TIDS [I], NULL, say_hello, NULL);
         IF (RET =! 0 ) 
        { 
           COUT << " pthread_create error: ERROR_CODE = " << RET << endl; 
        } 
    } 
    // after the thread exits each other, the process was ends, otherwise the process is forcibly terminated, the thread may not react; 
    pthread_exit (NULL); 
} 
use - lpthread library compiled the following program: 

$ G++ test.cpp -lpthread -o test.o
The following simple example code uses pthread_create () function creates 5 threads, and receive incoming parameters. Each thread prints a " the Hello Runoob! " Message and outputs the received parameters, and then call pthread_exit () to terminate the thread. 
#include <the iostream> 
#include <the cstdlib> 
#include <pthread.h> the using namespace STD; #define NUM_THREADS. 5 void * printHello ( void * ThreadID) 
{   // incoming parameters cast by untyped pointer integers pointer becomes then read int TID * = (( int * ) ThreadID); 
   COUT << " ! Runoob the Hello thread ID, " << << TID
 
 
 

 

   
   endl; 
   the pthread_exit (NULL); 
} 
 
int main () 
{ 
   pthread_t Threads [NUM_THREADS]; 
   int Indexes [NUM_THREADS]; // with the array to hold the value of i 
   int RC;
    int i;
    for (i = 0 ; i <NUM_THREADS; ++ i ) {       
      cout << " main (): creates a thread, " << i << endl; 
      the Indexes [i] = i; // first save the value of i
       // passed in time must be cast to void * type, That is untyped pointer         
      RC = pthread_create (& Threads [I], NULL, 
                          printHello, (void *) & (Indexes [I]));
       IF (RC) { 
         COUT << " Error: Unable to create a thread, " << RC << endl; 
         Exit ( - . 1 ); 
      } 
   } 
   the pthread_exit (NULL); 
}
Can pass any type of data callback thread, because it points to void , as shown in the following example: 
#include <the iostream> 
#include <the cstdlib> 
#include <pthread.h> the 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 << " the 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 = (char*)"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);
}
You can use the following two functions to connect or separate threads: 
pthread_join (threadid, Status) 
pthread_detach (threadid) 
pthread_join () subroutine obstruct the calling program until the specified thread terminates threadid. When a thread is created, it's an attribute defines whether it is connected (joinable) or detachable (detached). Defined only create threads that can be connected can be connected. If a thread is created is defined as separable, it can never be connected. 
#include <the iostream> 
#include <the cstdlib> 
#include <pthread.h> 
#include <unistd.h> the using namespace STD; #define NUM_THREADS. 5 void * the 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);
}

 

Guess you like

Origin www.cnblogs.com/tszr/p/12150118.html