The following is an example. We create two threads to increase the number of threads.
Maybe this instance has no practical value, but with a slight change, we can use it elsewhere.
# Include <pthread. h> <br/> # include <stdio. h> <br/> # include <sys/time. h> <br/> # include <string. h> <br/> # define max 10 </P> <p> pthread_t thread [2]; <br/> pthread_mutex_t mut; <br/> int number = 0, i; </P> <p> void * thread1 () <br/> {<br/> printf ("thread1: I'm thread 1/N "); </P> <p> for (I = 0; I <Max; I ++) <br/> {<br/> printf ("thread1: number = % d/N ", number); <br/> pthread_mutex_lock (& MUT); <br/> Number ++; <br/> Pthread_mutex_unlock (& MUT); <br/> sleep (2); <br/>}</P> <p> printf ("thread1: is the main function waiting for me to complete the task? /N "); <br/> pthread_exit (null); <br/>}</P> <p> void * thread2 () <br/>{< br/> printf ("thread2: I'm thread 2/N"); </P> <p> for (I = 0; I <Max; I ++) <br/>{< br/> printf ("thread2: Number = % d/N", number ); <br/> pthread_mutex_lock (& MUT); <br/> Number ++; <br/> pthread_mutex_unlock (& MUT); <br/> sleep (3 ); <br/>}</P> <p> printf ("thread2: is the main function waiting for me to complete the task? /N "); <br/> pthread_exit (null); <br/>}</P> <p> void thread_create (void) <br/>{< br/> int temp; <br/> memset (& Thread, 0, sizeof (thread )); // comment1 </P> <p> // create a thread <br/> If (temp = pthread_create (& Thread [0], null, thread1, null ))! = 0) // comment2 <br/> printf ("thread 1 creation failed! /N "); <br/> else <br/> printf (" thread 1 created/N "); </P> <p> If (temp = pthread_create (& Thread [1], null, thread2, null ))! = 0) // comment3 <br/> printf ("thread 2 creation failed "); <br/> else <br/> printf ("thread 2 created/N"); <br/>}</P> <p> void thread_wait (void) <br/>{< br/> // wait for the end of the thread <br/> If (thread [0]! = 0) // comment4 <br/>{< br/> pthread_join (thread [0], null ); <br/> printf ("thread 1 has ended/N"); <br/>}< br/> If (thread [1]! = 0) // comment5 <br/>{< br/> pthread_join (thread [1], null ); <br/> printf ("thread 2 has ended/N"); <br/>}</P> <p> int main () <br/>{< br/> // use the default attribute to initialize the mutex lock <br/> pthread_mutex_init (& Mut, null ); </P> <p> printf ("I am the main function, I am creating a thread, huh/N"); <br/> thread_create (); </P> <p> printf ("I am the main function. I am waiting for the thread to complete the task. Ah, haha/N"); <br/> thread_wait (); </P> <p> return 0; <br/>}< br/>
Next let's compile and execute:
$ Gcc-lpthread-O thread_example thread_example.c
$./Thread_example
I am a main function. I am creating a thread.
Thread 1 is created
Thread 2 is created
I am the main function. I am waiting for the thread to complete the task.
Thread1: I'm thread 1
Thread1: Number = 0
Thread2: I'm thread 2
Thread2: Number = 1
Thread1: Number = 2
Thread2: Number = 3
Thread1: Number = 4
Thread2: Number = 5
Thread1: Number = 6
Thread1: Number = 7
Thread2: Number = 8
Thread1: Number = 9
Thread2: Number = 10
Thread1: is the main function waiting for me to complete the task?
Thread 1 has ended
Thread2: is the main function waiting for me to complete the task?
Thread 2 has ended
The annotations in the instance code should be clear. Next I will introduce several functions and variables mentioned above on the Internet for reference.
Thread-related operations
I. pthread_t
Pthread_t is defined in the header file/usr/include/bits/pthreadtypes. h:
Typedef unsigned long int pthread_t;
It is the identifier of a thread.
Ii. pthread_create
The pthread_create function is used to create a thread. Its prototype is:
Extern int pthread_create _ p (pthread_t * _ thread, _ const pthread_attr_t * _ ATTR,
Void * (* _ start_routine) (void *), void * _ Arg ));
The first parameter is the pointer to the thread identifier. The second parameter is used to set the thread attribute. The third parameter is the starting address of the thread running function, and the last parameter is the parameter of the running function. Here, our function thread does not need parameters, so the last parameter is set as a null pointer. We also set the second parameter as a null pointer to generate a thread with the default attribute. The setting and modification of thread attributes will be described in the next section. When the thread is successfully created, the function returns 0. If the value is not 0, the thread creation fails. The common error codes returned are eagain and einval. The former indicates that the system restricts the creation of new threads. For example, the number of threads is too large. The latter indicates that the second parameter indicates that the thread attribute value is invalid. After the thread is successfully created, the newly created thread runs the function with parameters 3 and 4, and the original thread continues to run the next line of code.
3. pthread_join pthread_exit
The pthread_join function is used to wait for the end of a thread. Function prototype:
Extern int pthread_join _ p (pthread_t _ th, void ** _ thread_return ));
The first parameter is the identifier of the waiting thread, and the second parameter is a user-defined pointer, which can be used to store the return value of the waiting thread. This function is a thread-blocking function. The function called will wait until the end of the waiting thread. When the function returns, the resources of the waiting thread will be reclaimed. There are two ways to end a thread. One is that the function ends and the thread that calls it ends, as in the preceding example; another method is to use the pthread_exit function. Its function prototype is:
Extern void pthread_exit _ p (void * _ retval) _ attribute _ (_ noreturn __));
The unique parameter is the return code of the function. As long as the second thread_return parameter in pthread_join is not null, this value will be passed to thread_return. Finally, it should be noted that a thread cannot be waited by multiple threads. Otherwise, the first thread that receives the signal will return success, and the other threads that call pthread_join will return the error code esrch.
In this section, we write a simple thread and master the three most commonly used functions pthread_create, pthread_join, and pthread_exit. Next, let's take a look at some common attributes of the thread and how to set these attributes.
Mutex lock
Mutex lock is used to ensure that only one thread is executing a piece of code within a period of time.
I. pthread_mutex_init
The pthread_mutex_init function is used to generate a mutex lock. The null parameter indicates that the default attribute is used. To declare a mutex lock for a specific attribute, call the pthread_mutexattr_init function. The pthread_mutexattr_setpshared function and the pthread_mutexattr_settype function are used to set the mutex lock attribute. The previous function sets the property pshared, which has two values: pthread_process_private and pthread_process_shared. The former is used to synchronize threads in different processes, and the latter is used to synchronize different threads in the process. In the preceding example, we use the default pthread_process _ private attribute. The latter is used to set mutex lock types. Optional types include pthread_mutex_normal, pthread_mutex_errorcheck, pthread_mutex_recursive, and pthread _ mutex_default. They define different on-board and unlock mechanisms. Generally, the last default attribute is used.
Ii. pthread_mutex_lock pthread_mutex_unlock pthread_delay_np
The pthread_mutex_lock statement starts to lock with mutex lock. Subsequent code is locked until pthread_mutex_unlock is called, that is, only one thread can call and execute the lock at a time. When a thread executes at pthread_mutex_lock, if the lock is used by another thread at this time, the thread is blocked, that is, the program will wait for another thread to release the mutex lock.
Note:
1 It should be noted that the above two sleep is not only for demonstration purposes, but also for the thread to sleep for a period of time, so that the thread releases the mutex lock and waits for another thread to use this lock. This problem is described in reference 1 below. But in Linux, it seems that there is no pthread_delay_np function (I tried it and prompted that the reference of this function is not defined), so I used sleep instead, however, another method is provided in Reference 2. It seems to be replaced by pthread_cond_timedwait, which provides an implementation method.
2 Please pay attention to the comments in the comment1-5, it took me a few hours to find out the problem.
Without comment1, comment4, and comment5, a segment error occurs during pthread_join. In addition, the above comment2 and comment3 are the root cause, so remember to write the full code. Because the above thread may not be successfully created, it is impossible to wait until the end of the thread, and a segment error occurs when pthread_join is used (access to the unknown memory zone ). In addition, when using memset, the string. h header file must be included.