Commonly used to create multithreaded functions under Linux pthread_create (pthread_t * thread, pthread_attr_t * attr, void * (*start_routine) (void*), void *args);
The first parameter is used to hold the thread information. The second parameter refers to the running properties of the new thread, which can be set to NULL, the third parameter is a custom thread function, and the fourth parameter is the parameter that the thread function needs to use, generally if you want to pass more than one argument, you can set it to the structure body (struct) type. Here we use variables of type int.
I'll focus on the problem of passing arguments when you create multiple threads with a for structure:
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define TH_POP 20
pthread_mutex_t Mutex;
pthread_t A_thread[th_pop];
void * Thread_func (void *args) {pthread_mutex_lock (&mutex);
int t_id = * (int*) args;
printf ("The ID of this thread is%d\n", t_id);
Pthread_mutex_unlock (&mutex);
Return (void*) NULL;
} void Init () {pthread_mutex_init (&mutex, NULL);
int i;
For (i=0 i<th_pop; i++) {pthread_create (&a_thread[i), NULL, Thread_func, &i);
}//wait the end of the threads;
For (i=0 i<th_pop; i++) {int res = Pthread_join (A_thread[i], NULL);
if (res!= 0) printf ("The thread ID:%d ends fail \ n", i);
} Pthread_mutex_destroy (&mutex);
int main () {init ();
return 0; }
Run Result:
huangcheng@ubuntu:~$./a.out The ID of this thread are 2 the ID of this thread are 8 the ID of this thread is
9< C4/>the ID of this thread are 9 the ID of this thread was the ID of this thread
I s the ID of this thread are the ID of this thread are the ID of this thread are the ID of this
Thread is the ID of the ' This thread ' is the ID of the ' This thread ' ID of this thread is the
I D of this thread are the ID of this thread are the ID of this thread is
20< C19/>the ID of this thread was the
ID of this thread is 20