In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Most people do not understand the knowledge of this article "how to create two threads in Linux to add a number", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to create two threads in Linux to achieve the addition of a number" article.
Code:
/ * thread_example.c: c multiple thread programming in linux * author: falcon * e-mail: tunzhj03@st.lzu.edu.cn * / # include # define max 10pthread_t thread [2]; pthread_mutex_t mut;int number=0, iTAC void * thread1 () {printf ("thread1: iSum thread1 / n"); for (I = 0; I < max; iSuppli +) {printf ("thread1: number=% draft", number) Pthread_mutex_lock (& mut); number++; pthread_mutex_unlock (& mut); sleep (2);} printf ("thread1: is the main function waiting for me to finish the task? / n "); pthread_exit (null);} void * thread2 () {printf (" thread2: IBM thread2 / n "); for (I = 0; I < max; iPart +) {printf (" thread2: number =% dapin ", number); pthread_mutex_lock (& mut); number++; pthread_mutex_unlock (& mut); sleep (3) } printf ("thread2: is the main function waiting for me to finish the task? / n "); pthread_exit (null);} void thread_create (void) {int temp; memset (& thread, 0, sizeof (thread)); / / comment1 / * create thread * / if ((temp = pthread_create (& thread [0], null, thread1, null)! = 0) / / comment2 printf (" Thread 1 creation failed! / n ") Else printf ("Thread 1 created / n"); if ((temp = pthread_create (& thread [1], null, thread2, null)! = 0) / / comment3 printf ("Thread 2 creation failed"); else printf ("Thread 2 created / n") } void thread_wait (void) {/ * waiting for thread to end * / if (thread [0]! = 0) {/ / comment4 pthread_join (thread [0], null); printf ("thread 1 has ended / n");} if (thread [1]! = 0) {/ / comment5 pthread_join (thread [1], null) Printf ("Thread 2 has ended / n");} int main () {/ * initialize the mutex with default attributes * / pthread_mutex_init (& mut,null); printf ("I am the main function, I am creating a thread, hehe / n"); thread_create (); printf ("I am the main function, I am waiting for the thread to complete the task, hehe / n") Thread_wait (); return 0;}
Let's compile and execute first.
Quotation:
Falcon@falcon:~/program/c/code/ftp$ gcc-lpthread-o thread_example thread_example.cfalcon@falcon:~/program/c/code/ftp$. / thread_example I am the main function, I am creating a thread, hehe thread 1 is created thread 2 is created I am the main function, I am waiting for the thread to complete the task Hehe thread1: Icomm thread 1thread1: number = 0thread2: Isimthread 2thread2: number = 1thread1: number = 2thread2: number = 3thread1: number = 4thread2: number = 5thread1: number = 6thread1: number = 7thread2: number = 8thread1: number = 9thread2: number = 10thread1: is the main function waiting for me to finish the task? Thread 1 has finished thread2: is the main function waiting for me to finish the task? Thread 2 has ended
Quotation:
Thread-related operation
One 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.
Two pthread_create
The function pthread_create is used to create a thread whose 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 properties, 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 takes no arguments, so the last parameter is set to a null pointer. We also set the second parameter to a null pointer, which will generate the thread of the default property. We will discuss the setting and modification of thread properties in the next section. When the thread is created successfully, the function returns 0. If it is not 0, the thread creation failed. The common error return codes are eagain and einval. The former indicates that the system restricts the creation of new threads, such as too many threads; the latter indicates that the value of the thread property represented by the second parameter is illegal. After the thread is created successfully, the newly created thread runs the function determined by parameters 3 and 4, 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 identifier of the waiting thread, and the second parameter is a user-defined pointer that can be used to store the return value of the waiting thread. This function is a thread blocking function, and the function that calls it will wait until the end of the waiting thread, and when the function returns, the resources of the waiting thread will be reclaimed. There are two ways to end a thread, one is, as in our example above, the function ends, so does the thread that calls it, and the other is through the function pthread_exit. Its function prototype is:
Extern void pthread_exit _ p ((void * _ retval)) _ attribute__ ((_ _ noreturn__))
The only argument is the function's return code, which is passed to thread_return as long as the second argument in pthread_join, thread_return, is not null. Finally, a thread cannot be waited by multiple threads, otherwise the first thread that receives the signal returns successfully, and the rest of the 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 correlation
Mutexes are used to ensure that only one thread is executing a piece of code at a time.
One pthread_mutex_init
The function pthread_mutex_init is used to generate a mutex. The null parameter indicates that the default property is used. If you need to declare a mutex for a specific property, you must call the function pthread_mutexattr_init. The functions pthread_mutexattr_setpshared and pthread_mutexattr_settype are used to set the mutex property. 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 this process. In the above example, we are using the default property pthread_process_ private. The latter is used to set the mutex type, and the optional types are pthread_mutex_normal, pthread_mutex_errorcheck, pthread_mutex_recursive, and pthread_mutex_ default. They define different upper place and unlock mechanism respectively. In general, the last default attribute is selected.
Two pthread_mutex_lock pthread_mutex_unlock pthread_delay_np
The pthread_mutex_lock declaration starts locking with mutexes, and the subsequent code is locked until pthread_mutex_unlock is called, that is, it can only be called and executed by one thread at a time. When a thread executes to the 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.
Note:
1 it is important to note that the above two sleep are not only for demonstration purposes, but also to let the thread sleep for a period of time, let the thread release the mutex and wait for another thread to use the lock. This problem is illustrated in reference 1 below. But there seems to be no pthread_delay_np function under linux (I tried it, prompting that there is no reference to this function), so I used sleep instead, but reference 2 gives another way, which seems to be replaced by pthread_cond_timedwait, which gives a way to implement it.
Please pay attention to the note comment1-5 inside, which took me several hours to find out.
If there is no comment1 and comment4,comment5, it will lead to segment errors in pthread_join. In addition, the above comment2 and comment3 are the root causes, so be sure to write the whole code. Because the above thread may not be created successfully, it is impossible to wait until that thread ends, and a segment error occurs when using pthread_join (an unknown memory area is accessed). In addition, when using memset, you need to include the string.h header file.
The above is about the content of this article on "how to create two threads in Linux to add to a number". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.