Http://blog.csdn.net/lzx_bupt/article/details/6913039
The previous examples show whether the attribute parameters are not mentioned when few threads are created. See the example below:
[CPP] View plaincopy
-
- # Include <iostream>
-
- # Include <pthread. h>
-
-
-
- # Include <iostream>
-
- # Include <pthread. h>
-
- Using NamespaceSTD;
-
-
- # Define num_threads 5
-
-
- Void* Say_hello (Void* ARGs)
-
- {
-
- Cout <"Hello in thread"<*((Int*) ARGs) <Endl;
- IntStatus = 10 + *((Int*) ARGs );// Add the parameter to 10
-
- Pthread_exit ((Void*) Status );// Because the joinable parameter is provided during thread creation, the exit information can be added here: status for the masterProgramExtract the end information of the thread;
-
- }
-
-
- IntMain ()
-
- {
-
- Pthread_t tids [num_threads];
- IntIndexes [num_threads];
-
-
- Pthread_attr_t ATTR;// To add parameters during creation, declare
-
- Pthread_attr_init (& ATTR );// Reinitialize
-
- Pthread_attr_setdetachstate (& ATTR, pthread_create_joinable );// After the declaration and initialization, the third step is to set the thread attribute parameter you want to specify. This parameter indicates that the thread can be joined, the join function indicates that the main program can wait for the thread to end before doing something. The main program and the thread synchronization function are implemented. This deep understanding must be illustrated to explain it. See other materials.
-
- For(IntI = 0; I <num_threads; ++ I)
-
- {
-
- Indexes [I] = I;
-
- IntRet = pthread_create (& tids [I], & ATTR, say_hello ,(Void*) & (Indexes [I]);// The four parameters are complete. More configuration information is required;
-
- If(Ret! = 0)
- {
-
- Cout <"Pthread_create error: error_code ="<RET <Endl;
-
- }
-
- }
-
-
- Pthread_attr_destroy (& ATTR );// The parameter can be destroyed after it is used up. It must be destroyed to prevent memory leakage;
-
-
- Void* Status;
- For(IntI = 0; I <num_threads; ++ I)
-
- {
-
- IntRet = pthread_join (tids [I], & status );// A thread is created before. Here, the main program wants to join each thread and obtain the exit information of each thread;
-
- If(Ret! = 0)
-
- {
- Cout <"Pthread_join error: error_code ="<RET <Endl;
-
- }
-
- Else
-
- {
-
- Cout <"Pthread_join get status :"<(Long) Status <Endl;
- }
-
- }
-
- }
Compile and run g ++-lpthread-O ex_join ex_join.cpp
Result:
[Plain] View plaincopy
- Hello in thread 4
- Hello in thread 3
- Hello in thread 2
- Hello in thread 1
- Hello in Thread 0
- Pthread_join get status: 10
- Pthread_join get status: 11
- Pthread_join get status: 12
- Pthread_join get status: 13
- Pthread_join get status: 14
Let's take a look at the join function.