Http://blog.csdn.net/lzx_bupt/article/details/6910632
The thread will be created. How do I pass in parameters when the thread calls a function? It should be as follows:
[CPP] View plaincopy
-
- # Include <iostream>
-
- # Include <pthread. h>
-
-
- Using NamespaceSTD;
-
-
- # Define num_threads 5
-
- Void* Say_hello (Void* ARGs)
-
- {
-
- IntI = *((Int*) ARGs );// Forcibly convert the input parameter type, from a non-type pointer to an integer pointer, and then read it;
-
- Cout <"Hello in"<I <Endl;
-
- }
-
-
- IntMain ()
-
- {
- Pthread_t tids [num_threads];
-
- Cout <"Hello in Main ..."<Endl;
-
- For(IntI = 0; I <num_threads; ++ I)
-
- {
-
- IntRet = pthread_create (& tids [I], null, say_hello ,(Void*) & I );// It must be forcibly converted to the void * type when passed in, that is, no type pointer
- Cout <"Current pthread id ="<Tids [I] <Endl;// Use the tids array to print the ID of the created process;
-
- If(Ret! = 0)
-
- {
-
- Cout <"Pthread_create error: error_code ="<RET <Endl;
-
- }
- }
-
-
- Pthread_exit (null );
-
- }
The result is as follows:
[Plain] View plaincopy
- Current pthread id = 139671233451792
- Current pthread id = 139671222961936
- Current pthread id = 139671212472080
- Current pthread id = 139671201982224
- Current pthread id = 139671191492368
- Hello, in 4196496
- Hello, in 4196496
- Hello, in 4196496
- Hello, in 4196496
- Hello, in 4196496
Have you found any problems? Yes, the I value does not output the expected results. This is due to multithreading. When the main process has not been assigned a value for I, the thread has started to run !~
Then the followingCodeIs correct:
[CPP] View plaincopy
-
- # Include <iostream>
-
- # Include <pthread. h>
-
-
- Using NamespaceSTD;
-
-
- # Define num_threads 5
-
-
- Void* Say_hello (Void* ARGs)
- {
-
- Cout <"Hello in thread"<*((Int*) ARGs) <Endl;
-
- }
-
-
- IntMain ()
-
- {
-
- Pthread_t tids [num_threads];
-
- IntIndexes [num_threads];// Use an array to save the I value.
-
- For(IntI = 0; I <num_threads; ++ I)
-
- {
-
- Indexes [I] = I;// Save the I value first, so the problem will not occur in the calling thread.
-
- IntRet = pthread_create (& tids [I], null, say_hello ,(Void*) & (Indexes [I]);
-
- If(Ret! = 0)
- {
-
- Cout <"Pthread_create error: error_code ="<RET <Endl;
-
- }
-
- }
-
- For(IntI = 0; I <num_threads; ++ I)
-
- Pthread_join (tids [I], null );
-
- }
Compile and run: (SourceProgramRemove the nonsense of printing thread ID)
[Plain] View plaincopy
- [CPP @ node2 pthread] $./ex_create_args_ OK
- Hello in thread 3
- Hello in thread 4
- Hello in thread 2
- Hello in thread 1
- Hello in Thread 0