Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to treat the semaphore Semaphore in Linux multithreading

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

Today, I will talk to you about how to treat the semaphore Semaphore in Linux multithreading. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

Understand Semaphore and start with a good translator

Semaphore, anyone who has known about multithreading has heard of it, which is generally interpreted as "semaphore". However, this word is still strange to us. What does it have to do with another word, Singal? If you want to really understand this concept, you must start with its translation. In fact, the best translation of Semaphore should be "semaphore quantity". Admitting this, you must be clear: it is not the same thing as Signal!

The translation of Cambridge dictionary is not easy to understand.

Signal: simply a message, which is the information sent by the user, system, or process to the target process to notify the target process of a state change or system exception, corresponding to an asynchronous scenario (which I described in detail in my previous article).

Semaphore: first is a variable, followed by a counter. It is a facility used in a multithreaded environment, and the semaphore needs to be created with an initial value, indicating that several tasks (threads) can access a shared resource at the same time.

If a task wants to access a shared resource, the semaphore is greater than 0. When the task successfully acquires the resource, subtract the semaphore by 1.

If the value of the current semaphore is less than 0, indicating that the semaphore cannot be obtained, the task must be suspended and wait for the semaphore to return to positive value.

When the task is finished, the semaphore must be released, and the corresponding operation is to add 1 to the value of the semaphore.

In addition, the operations on semaphores (addition and subtraction) are atomic. Mutex (Mutex) is a special case when the initial value of semaphore is 1, that is, only one task can access the shared resource area at a time.

Semaphore will understand again

Let's imagine such a scene (above): if there is a free concert at the National Grand Theater in Beijing, but it is during the epidemic, the theater rules: the total audience size of the theatre should be limited, but everyone is allowed to exit midway. give the tickets to others, and others can come in midway. As a result, the first batch of people who arrived first got the tickets from the ticket box at the entrance of the theatre and then entered to enjoy the performance. Those who arrived later waited at the door because the theatre was full. After a period of time, someone thought the program was too boring and left early. When he left the show, he put the ticket back. In this way, the others came in with this man's ticket. Then there was another exit, but he forgot to put the ticket back. It doesn't matter, it's just one less than the total number of people that can be accommodated in the theatre.

In the above example, the concert site is a shared resource area, the audience is the task (thread), and the number of tickets in the ticket box is the semaphore. The semaphore is used as a concurrency limit, and since the total number of tickets is fixed, there will be no overcrowding in the concert hall.

In the above example, we allow the exiting audience to take the tickets away. Why? Because the theater staff can replenish some tickets in the ticket box at any time (thread producer). Speaking of which, aren't you guys a little familiar? That's right, it's the thread pool, but it's still a little different. Taste it for yourself.

Semaphore practical exercises

The semaphore type is sem_t, and the type and related operations are defined in the header file semaphore.h

Create semaphore

Int sem_init (sem_t * sem, int pshared, unsigned int value)

Add 1 to the value of the semaphore

Int sem_post (sem_t * sem)

The value of the semaphore minus 1

Int sem_wait (sem_t * sem)

Semaphore destruction

Int sem_destroy (sem_t * sem)

The meaning of the specific parameters and the return value will not be discussed here. An example is shown below:

You have a total of three types of download tasks (type id is 1, 2, 3), one type of task is read from the keyboard at a time to download, but CPU can perform up to 2 download tasks at the same time (create two threads).

# include # define MAXNUM (2) sem_t semDownload; pthread_t a_thread, b_thread, clockthread; int g_phreadNum = 1; void func1 (void * arg) {/ / wait semaphore value > 0 sem_wait (& semDownload); printf ("= Downloading taskType 1 =\ n"); sleep (5); printf ("= Finished taskType 1 =\ n") / wait for the thread to end pthread_join (a_thread, NULL);} void func2 (void * arg) {sem_wait (& semDownload); printf ("= Downloading taskType 2 =\ n"); sleep (3); printf ("= Finished taskType 2 =\ n"); pthread_join (b_thread, NULL);} void func3 (void * arg) {sem_wait (& semDownload) Printf ("= Downloading taskType 3 =\ n"); sleep (1); printf ("= Finished taskType 3 =\ n"); pthread_join (c_thread, NULL);} int main () {/ / initialize semaphore sem_init (& semDownload, 0,0); int taskTypeId While (scanf ("% d", & taskTypeId)! = EOF) {/ / enter 0 to test whether the program can exit if (taskTypeId = = 0 & & g_phreadNum MAXNUM) {printf ("! You've reached the max number of threads!!\ n "); continue;} / / user chooses to download Task switch (taskTypeId) {case 1: / / create thread 1 pthread_create (& a_thread, NULL, func1, NULL) / / semaphore + 1, which in turn triggers the task of func1 sem_post (& semDownload); / / number of buses + 1 g break; case phreadNumbers; break; case 2: pthread_create (& b_thread, NULL, func2, NULL); sem_post (& semDownload); GrouphreadNumbers + Break; case 3: pthread_create (& c_thread, NULL, func3, NULL); sem_post (& semDownload); break; default: printf ("! Error taskTypeId% d!!\ n ", taskTypeId); break;}} / / destroy semaphore sem_destroy (& semDownload); return 0;}

In the above example, the method of pthread_join () is used, that is, the child thread merges into the main thread, the main thread blocks and waits for the child thread to finish, and then reclaims the child thread resources. There is another way to join the thread: pthread_detach (), that is, the main thread is separated from the child thread, and the main thread does not have to worry about when the child thread ends. After the child thread ends, the resources are automatically reclaimed.

The running result of the program is as follows:

Also note that the default library for pthread.h non-linux systems, gcc compilation parameters need to be manually added options:-lpthread,-pthread.

After reading the above, do you have any further understanding of how to view the semaphore Semaphore in Linux multithreading? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

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: 237

*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.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report