Table of Contents
(reposted) Interesting article: I am a thread, interesting article I am a thread
Home Backend Development PHP Tutorial (Transfer) Interesting article: I am a thread, interesting article I am a thread_PHP tutorial

(Transfer) Interesting article: I am a thread, interesting article I am a thread_PHP tutorial

Jul 12, 2016 am 08:54 AM
thread

(reposted) Interesting article: I am a thread, interesting article I am a thread

From: Coder Turnover (WeChat ID: codingrising )

Author: IBM Liu Xin 

I am a thread. I was assigned a number: 0x3704 when I was born. Then I was led to a dark room, where I found many companions who were exactly like me.

My companion 0x6900 stayed for a long time. He said to me with a vicissitude of life:

The destiny of our thread is to process packages. You have to come back here immediately after handling the package, otherwise you may never come back.

I’m confused, package, what package?

"Don't be anxious, you will understand soon, we don't care for idlers here."

Sure enough, not long after, the door of the house opened, and a fierce-looking guy shouted:

"0x3704, come out!"

As soon as I came out, I was stuffed with a heavy package, and there was a piece of paper with instructions written on it.

"Go quickly and get rid of this package."

"Where to deal with it"

"Follow the instructions and get to the ready workshop first"

Sure enough, there was an indicator arrow on the ground, and I followed it to a large, bright room. There were already many threads here. Everyone was very nervous, as if they were always ready to rush forward.

As soon as I came in, I heard the announcement: "0x3704, enter the workshop"

I walked forward quickly, and many people behind me talked and said:

"He is so lucky, he can run as soon as he enters the ready state"

“Does it matter?”

“No, look at how high their priority is, ugh”

In front is the workshop. It is so beautiful here. No wonder the old thread always nags: It would be great if I could stay here forever.

The space here is large, the view is good, the air is fresh, the birds are singing and the flowers are fragrant, and there are many people I have never seen before, waiting to serve me like waiters.

They also have numbers, and more importantly, each one has a label, which reads: hard disk, database, memory, network card. . .

I can’t understand it now, let’s take a look at the steps:

Step 1: Take out the parameters from the package

Open the package, there is an HttpRequest object inside, you can get the two parameters userName and password

Step 2: Perform login operation

Oh, it turned out that someone wanted to log in. I handed the userName/password to the database attendant. He took the data and walked away slowly.

Why is he so slow? But can I just stay in the workshop for a while? I can't perform the third step anyway.

At this moment, the radio in the workshop rang:

"0x3704, I am CPU, remember the steps you are performing, and leave with the package immediately"

I slowly started to pack up

"Hurry up, other threads will come in soon"

Leaving this workshop, I came to a big room again, where many threads were slowly drinking tea and playing cards.

"Brother, you have nothing to do?"

"You're new here, you don't know that I'm waiting for the database server to give me the data! It is said that they are hundreds of thousands of times slower than us, take a good rest here"

"Huh? So slow? Someone here is logging into the system. Can you wait for so long?"

" Don't worry, haven't you heard that one day on earth is equivalent to one year on CPU? We use nanoseconds and milliseconds to measure time here. One second on earth is equivalent to several days for us. It's just in time"

Just take a nap. I don’t know how long it took, but the loudspeaker started broadcasting again:

"0x3704, your data is here, go and execute it"

I turned around and ran to the CPU workshop, only to find that people here could only get in and out!

There were bursts of laughter from behind:

"She is indeed a newbie, I don’t know that I have to go to the ready workshop to wait"

So I hurried to the ready workshop. This time I was not so lucky. I waited for a long time before being called into the CPU workshop again.

While waiting, I heard someone whispering:

"Have you heard that a thread was killed recently?"

"Why?"

"This guy stayed in the CPU workshop and kept pushing the CPU utilization to 100%, and then he was killed"

"Where did the Kill go after it was dropped?"

”Maybe it was garbage collected”

I shuddered in my heart, and quickly continued processing. I accepted more action blocks, and the second step of login was successful

Step 3: Build the homepage after successful login

This step is a bit time-consuming, because there is a lot of HTML to process, and I don’t know who wrote the code, so it is very annoying to process.

I was nervously making HTML, and the CPU started to beep:

"0x3704, I am CPU, remember the steps you are performing, and leave with the package immediately"

"Why?"

"Each thread can only run on the CPU for a period of time. When the time is up, it must be used by others. You go to the ready workshop and wait for me to call you."

That’s it, I have been in the two states of Ready and Running. I don’t know how many times it has been rotated, and finally the installation step list has completed the work.

Finally, the package containing html was successfully sent back.

As for what you do after logging in, I don’t care.

I’m going back to my dark room soon. I really can’t bear to leave here.

But compared to some threads, I am still lucky. They are completely destroyed after running, and I am still alive!

Back in the dark room, old thread 0x6900 asked:

"How was it? How did you feel on the first day?"

”The rules of our world are very complicated. First of all, you don’t know when you will be selected for execution; second, you may be interrupted at any time during the execution process and give up the CPU workshop;

"

"Young man understands well"

”I don’t understand why many threads die after executing, why are we still alive?”

”You still don’t know, immortality is our privilege, we have an official name here, called thread pool!”

The ordinary days pass like this day by day. As a thread, my daily life is to pick up packages, process packages, and then return to our dim home: the thread pool.

When I came back one day, I heard a brother say, I need to have a good rest today, tomorrow will be the craziest day.

I looked at the calendar, tomorrow is November 11th.

Sure enough, just after midnight, I don’t know what happened to those humans. They were frantically delivering packages. In order to cope with the massive influx of packages, no one in the thread pool could be idle. They all went out to process the packages. The utilization rate of the CPU workshop exceeded High, the hard drive is humming, and the network card is flashing like crazy. Even so, it still can't be processed, and it piles up like a mountain.

We have no choice, there are just too many. Most of these packages are just browsing the page, placing orders, buying, buying, buying.

I don’t know how long it took, but Bao Bao Mountain finally slowly disappeared.

Finally able to take a breath, I think I will never forget this day.

Through this incident, I understood the world I live in: this is an e-commerce website!

My daily job is to handle user login, browsing, shopping cart, ordering, and payment.

I asked the thread pool veteran 0x6900: "How long do we have to work?"

"You have to wait until the system restarts", 0x6900 said

"Have you ever experienced a system reboot?"

" How is it possible? , System restart is our moment of death, that is, the end of the world. Once restarted, the entire thread pool will be destroyed, time and space will disappear, and everything will start all over again"

"When will it restart?"

"It’s hard to say, just enjoy the life in front of you..."

In fact, life is rich and colorful. My favorite package is uploading pictures. Due to the slow network, I can stay in the ready workshop and CPU workshop for a long time, and I can get to know many interesting threads.

For example, last time I met the memecached thread, he told me that a lot of user data was cached through him, and it was distributed! It’s available on many machines!

I said no wonder the subsequent login operation was so much faster. It turns out that the data is no longer fetched from the database. You have it there. Oh, by the way, you are distributed. Have you been to other machines?

He said how is it possible that I can only send a GET and PUT command to that machine through the network every time to access data, and I don’t know anything else.

For example, last time I encountered a database connection thread while waiting, I learned that it also has a connection pool, which is almost exactly the same as our thread pool.

He said some packages were so perverted that he even checked a year’s worth of order data, which exhausted me to death.

I said I’ll knock you down. That’s pure data. After you pass the data to me, I have to assemble it into HTML. The workload is many times greater than yours.

He said that you must have a good relationship with memecached, get data directly from him, and make as few direct calls to the database as possible, so that our JDBC connection can live more easily.

I said yes, yes, the key is that you have to get the data to the cache in advance. Otherwise, if I ask the cache first and there is no data, don’t I still have to find you?

Life is like this, if you don’t have some fun, what’s the point?

One day I encountered a terrible thing. I almost died outside and could not return to the thread pool...

Actually, I should have been able to predict this danger, but I was too careless.

A few days ago I processed some deposit and withdrawal packages sent from http. The old thread 0x6900 specifically asked me:

"Be especially careful when handling these packages. You must obtain a lock first. You must lock the account when depositing or withdrawing money from the account, otherwise Other threads will take advantage of you while you are waiting and cause damage. I was very rough when I was young, so I took advantage of it."

In order to "scare" me, the kind 0x6900 also gave me two forms:

1. Without locking

2. Locking situation

I was horrified to see that not locking the door would cause such a serious accident.

From now on, I will be more careful when I see the packages for deposits and withdrawals. Fortunately, there have been no accidents.

A package I received today was a money transfer from a famous actor’s account to a famous director. I won’t reveal who it is, but the amount is really not small

I follow the instructions of the old thread and must lock it. First, I will lock the account of a famous actor, and then I will lock the account of a famous director.

But what I never expected was that there was another thread, yes, it was 0x7954, which was transferring money from the director to the actor at the same time.

So, this happened:

I didn’t know what was going on at first, so I kept sitting in the waiting workshop and waiting, but the waiting time was too long, as long as dozens of seconds! I've never experienced anything like this.

At this time I saw thread 0x7954, he was sitting there leisurely drinking coffee, and I started chatting with him:

“Brother, I see you have drank 8 cups of coffee, why don’t you go to work?”

"Didn't you drink 9 cups of tea?" 0x7954 replied.

“I’m waiting for a lock, but I don’t know which grandson won’t release it”

"I am also waiting for the lock. If I know which grandson will not release the lock, I will beat him to death." 0x7954 shows no weakness.

I glanced secretly, didn’t this guy hold the director’s lock that I was waiting for in his arms?

Obviously, 0x7954 also spotted me holding the lock he was waiting for.

Soon the two of us started to quarrel, refusing to give in to each other :

"Give me your lock first and let me finish it first"

"No, I always release the lock after finishing the work. I definitely can't give it to you now"

From quarrel to fight, it only takes a few seconds.

More importantly, the two of us not only hold the lock of this famous director and actor, but also have many other locks, resulting in more and more waiting threads, and the room is packed with people watching.

Things really got big in the end, and the ultimate boss "Operating System", which I have never seen before, also came.

The Big Boss is well-informed after all. He took one look at it, snorted, and said disdainfully:

"Deadlock occurs again"

"You two want to kill one of them, come on, come and draw lots"

This moment scared me to the point of peeing. It’s so serious!

I drew the lot cautiously, opened it and saw that it was the word "living".

Alas, my life was finally saved.

After poor 0x7954 was forced to hand over all his resources, he was unfortunately killed and disappeared.

I got the director’s lock and can start working.

The Big Boss operating system disappeared like a gust of wind, and only his voice came from behind:

Remember, here we are directors>actors, regardless of their acquaintance status, they must first obtain the director's lock

Since there are not only directors and actors, but also many other people, Boss left a table, which is an algorithm used to calculate the size of resources. After calculation, it will always be obtained from large to small. Lock:


I returned to the thread pool. Everyone knew about my adventure and asked me questions non-stop.

The vicious thread scheduler posted the Big Boss algorithm on the wall.

Every morning, like unscrupulous real estate agents or waiters at beauty salons, we have to stand at the door and recite loudly:

"Be sure to keep in mind when locking multiple resources. You must compare the sizes according to the boss's algorithm, and then lock them starting from the largest one."

------------------------------------------------- ----------

After many days, other threads and I discovered a strange thing: the processing of packages is getting easier and easier

No matter what package, whether it is logging in, browsing, saving money... the processing steps are the same, and a fixed html page is returned

Once I took a sneak peek and it read:

"This system will be undergoing maintenance and upgrades from 00:00 to 4:00 tonight. We are deeply sorry for the inconvenience caused to you"

I told the old thread 0x6904, he sighed and said:

"Alas, our lives have come to an end. It seems that the system will be restarted soon and we will disappear. Goodbye, brother."

The moment for system restart has finally arrived.

I saw that everything in the house was disappearing one by one. The waiting workshop, ready workshop, and even the CPU workshop were slowly disappearing.

There are fewer and fewer thread brothers around me, and finally I am the only one left.

I shouted in the open field: Is there anyone else?

No answer.

Our generation thread pool has completed its mission.

The next generation thread pool will be reborn soon.

(End)

If you have learned something from reading this article, please give me a thumbs up . If there are any errors in the article, please point it out.

Learn from each other and make progress together!

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1121387.htmlTechArticle (reposted) Interesting article: I am a thread, interesting article I am a thread from: Coder Turnaround (WeChat ID : coding) Author: IBM Liu Xin I am a thread, I was assigned a number when I was born:...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What does 8 cores and 16 threads mean? What does 8 cores and 16 threads mean? Feb 02, 2023 am 11:26 AM

8-core means that the CPU has 8 physical cores, and 16-thread means that the CPU can have up to 16 threads processing tasks at the same time. The number of cores and threads are important performance indicators of a computer CPU. The higher the number of cores of the CPU, the higher the processing speed; the higher the number of threads, the more conducive it is to running multiple programs at the same time, because the number of threads is equivalent to the number of times the CPU can run at the same time at a certain moment. The number of tasks to be processed in parallel. Multi-threading can maximize wide-issue, out-of-order superscalar processing, improve the utilization of processor computing components, and alleviate memory access delays caused by data correlation or cache misses.

C++ Concurrent Programming: How to avoid thread starvation and priority inversion? C++ Concurrent Programming: How to avoid thread starvation and priority inversion? May 06, 2024 pm 05:27 PM

To avoid thread starvation, you can use fair locks to ensure fair allocation of resources, or set thread priorities. To solve priority inversion, you can use priority inheritance, which temporarily increases the priority of the thread holding the resource; or use lock promotion, which increases the priority of the thread that needs the resource.

C++ Concurrent Programming: How to do thread termination and cancellation? C++ Concurrent Programming: How to do thread termination and cancellation? May 06, 2024 pm 02:12 PM

Thread termination and cancellation mechanisms in C++ include: Thread termination: std::thread::join() blocks the current thread until the target thread completes execution; std::thread::detach() detaches the target thread from thread management. Thread cancellation: std::thread::request_termination() requests the target thread to terminate execution; std::thread::get_id() obtains the target thread ID and can be used with std::terminate() to immediately terminate the target thread. In actual combat, request_termination() allows the thread to decide the timing of termination, and join() ensures that on the main line

What is the smallest unit of instruction flow when a program is running? What is the smallest unit of instruction flow when a program is running? Aug 23, 2022 pm 02:16 PM

"Thread" is the smallest unit of instruction flow when a program is running. A process refers to a program with certain independent functions, and a thread is a part of the process, describing the execution status of the instruction flow; the thread is the smallest unit of the instruction execution flow in the process, and is the basic unit of CPU scheduling. A thread is an execution process of a task (a program segment); a thread does not occupy memory space, it is included in the memory space of the process. Within the same process, multiple threads share the process's resources; a process has at least one thread.

What is the difference between coroutines and threads in go language What is the difference between coroutines and threads in go language Feb 02, 2023 pm 06:10 PM

Differences: 1. A thread can have multiple coroutines, and a process can also have multiple coroutines alone; 2. Threads are a synchronization mechanism, while coroutines are asynchronous; 3. Coroutines can retain the state of the last call, Threads do not work; 4. Threads are preemptive, while coroutines are non-preemptive; 5. Threads are divided CPU resources, and coroutines are organized code processes. Coroutines require threads to host and run.

Java Error: JavaFX thread stuck error, how to deal with and avoid it Java Error: JavaFX thread stuck error, how to deal with and avoid it Jun 24, 2023 pm 05:52 PM

During the development of JavaFX applications, we often encounter JavaFX thread stuck errors. Such errors vary in severity and may adversely affect program stability and performance. In order to ensure the normal operation of the program, we need to understand the causes and solutions of JavaFX thread stuck errors, and how to prevent this error from occurring. 1. The cause of JavaFX thread stuck error. JavaFX is a multi-threaded UI application framework, which allows programs to execute for a long time in background threads.

Analysis of the difference between threads and processes in Go language Analysis of the difference between threads and processes in Go language Apr 03, 2024 pm 01:39 PM

Processes and threads in Go language: Process: an independently running program instance with its own resources and address space. Thread: An execution unit within a process that shares process resources and address space. Features: Process: high overhead, good isolation, independent scheduling. Threads: low overhead, shared resources, internal scheduling. Practical case: Process: Isolating long-running tasks. Threads: Process large amounts of data concurrently.

Microsoft plans to introduce AI-powered Copilot to Outlook classic app on Windows Microsoft plans to introduce AI-powered Copilot to Outlook classic app on Windows Oct 19, 2023 pm 11:13 PM

Microsoft apparently won't keep its powerful AI-powered Copilot tool as an exclusive feature of the new app. Now, the company has just announced plans to bring Copilot to the Outlook classic app on Windows. As posted on its 365 Roadmap website, previews will begin in March next year and will roll out globally on desktops in the current channel until March. Copilot is a productivity tool that uses large language models (LLMs) to help users with tasks such as writing emails, summarizing documents, and translating languages. One of its main features is its ability to summarize emails

See all articles