Let’s take an example first. We create two threads to increment a number. Maybe this example has no practical value, but with a slight change, we can use it in other places.
Code:
/*thread_example.c : c multiple thread programming in linux *author : falcon *e-mail : tunzhj03@st.lzu.edu.cn */ #include <pthread.h> #include <stdio.h> #include <sys/time.h> #include <string.h> #define max 10 pthread_t thread[2]; pthread_mutex_t mut; int number=0, i; void *thread1() { printf ("thread1 : i'm thread 1/n"); for (i = 0; i < max; i++) { printf("thread1 : number = %d/n",number); pthread_mutex_lock(&mut); number++; pthread_mutex_unlock(&mut); sleep(2); } printf("thread1 :主函数在等我完成任务吗?/n"); pthread_exit(null); } void *thread2() { printf("thread2 : i'm thread 2/n"); for (i = 0; i < max; i++) { printf("thread2 : number = %d/n",number); pthread_mutex_lock(&mut); number++; pthread_mutex_unlock(&mut); sleep(3); } printf("thread2 :主函数在等我完成任务吗?/n"); pthread_exit(null); } void thread_create(void) { int temp; memset(&thread, 0, sizeof(thread)); //comment1 /*创建线程*/ if((temp = pthread_create(&thread[0], null, thread1, null)) != 0) //comment2 printf("线程1创建失败!/n"); else printf("线程1被创建/n"); if((temp = pthread_create(&thread[1], null, thread2, null)) != 0) //comment3 printf("线程2创建失败"); else printf("线程2被创建/n"); } void thread_wait(void) { /*等待线程结束*/ if(thread[0] !=0) { //comment4 pthread_join(thread[0],null); printf("线程1已经结束/n"); } if(thread[1] !=0) { //comment5 pthread_join(thread[1],null); printf("线程2已经结束/n"); } } int main() { /*用默认属性初始化互斥锁*/ pthread_mutex_init(&mut,null); printf("我是主函数哦,我正在创建线程,呵呵/n"); thread_create(); printf("我是主函数哦,我正在等待线程完成任务阿,呵呵/n"); thread_wait(); return 0; }
Let’s compile and execute it first
Quotation:
falcon@falcon:~/program/c/code/ftp$ gcc -lpthread -o thread_example thread_example.c falcon@falcon:~/program/c/code/ftp$ ./thread_example 我是主函数哦,我正在创建线程,呵呵 线程1被创建 线程2被创建 我是主函数哦,我正在等待线程完成任务阿,呵呵 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 :主函数在等我完成任务吗? 线程1已经结束 thread2 :主函数在等我完成任务吗? 线程2已经结束
The comments in the example code should be clearer, below I have quoted several functions and variables mentioned above on the Internet.
Citation:
Thread related operations
一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.
二pthread_create
The function pthread_create 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 a pointer to the thread identifier, the second parameter is used to set the thread attributes, and the third parameter is the start of the thread running function. The starting address, the last parameter is the parameter to run the function. Here, our function thread does not require parameters, so the last parameter is set to a null pointer. We also set the second parameter to a null pointer, which will generate a thread with default attributes. We will explain the setting and modification of thread attributes in the next section. When the thread is created successfully, the function returns 0. If it is not 0, the thread creation fails. Common error return codes are eagain and einval. The former means that the system restricts the creation of new threads, for example, the number of threads is too many; the latter means that the thread attribute value represented by the second parameter is illegal. After the thread is successfully created, the newly created thread runs the function determined by parameter three and parameter four, and the original thread continues to run the next line of code.
Three pthread_join pthread_exit
The function pthread_join is used to wait for the end of a thread. The function prototype is:
extern int pthread_join __p ((pthread_t __th, void **__thread_return));
The first parameter is the thread identifier to be waited for, and the second parameter is a user-defined pointer. Can be used to store the return value of the waiting thread. This function is a thread-blocking function. The function calling it will wait until the waiting thread ends. When the function returns, the resources of the waiting thread are recovered. There are two ways to end a thread. One is like our example above. When the function ends, the thread that called it also ends. The other way is through the function pthread_exit. Its function prototype is:
extern void pthread_exit __p ((void *__retval)) __attribute__ ((__noreturn__));
The only parameter is the return code of the function, as long as the second parameter thread_return in pthread_join is not null , this value will be passed to thread_return. The last thing to note is that a thread cannot be waited by multiple threads, otherwise the first thread that receives the signal returns successfully, and the remaining threads that call pthread_join return the error code esrch.
In this section, we wrote the simplest thread and mastered the three most commonly used functions pthread_create, pthread_join and pthread_exit. Next, let's take a look at some common properties of threads and how to set them.
Mutex lock related
Mutex lock is used to ensure that only one thread is executing a piece of code within a period of time.
一pthread_mutex_init
The function pthread_mutex_init is used to generate a mutex lock. The null parameter indicates that the default properties are used. If you need to declare a mutex for a specific attribute, you must call the function pthread_mutexattr_init. The function pthread_mutexattr_setpshared and the function pthread_mutexattr_settype are used to set the mutex lock attributes. The previous function sets the attribute 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 this process. In the above example, we are using the default attribute pthread_process_private. The latter is used to set the mutex lock type. The optional types are pthread_mutex_normal, pthread_mutex_errorcheck, pthread_mutex_recursive and pthread _mutex_default. They respectively define different listing and unlocking mechanisms. Under normal circumstances, the last default attribute is selected.
2 pthread_mutex_lock pthread_mutex_unlock pthread_delay_np
The pthread_mutex_lock statement starts to lock with a mutex lock. The subsequent code is locked until pthread_mutex_unlock is called, that is, it can only be called and executed by one thread at the same time. When a thread executes to pthread_mutex_lock, if the lock is used by another thread at this time, the thread is blocked, that is, the program will wait until another thread releases the mutex lock.
Notice:
1 It should be noted that the above two sleeps are not only for demonstration purposes, but also to let the thread sleep for a period of time, let the thread release the mutex lock, and wait for another thread to use this lock. This problem is explained in Reference 1 below. However, there seems to be no pthread_delay_np function under Linux (I tried it and it was prompted that there is no reference to the function defined), so I used sleep instead. However, another method is given in Reference 2, which seems to be replaced by pthread_cond_timedwait. , which gives a way to achieve it.
2 Please pay attention to the comments1-5 inside, that is where the problem took me several hours to find out.
If there are no comment1, comment4, and comment5, it will cause a segfault during pthread_join. In addition, the above comment2 and comment3 are the root cause, so be sure to remember to write the entire code. Because the above thread may not be created successfully, it is impossible to wait for the thread to end, and a segmentation fault occurs (an unknown memory area is accessed) when using pthread_join. In addition, when using memset, you need to include the string.h header file
The above is the detailed content of Linux multi-threaded programming example code analysis. For more information, please follow other related articles on the PHP Chinese website!